2017-10-01 10 views
0

Si je configure un cond où l'expression dans une branche correspondante appelle (str), j'obtiens un ClassCastException. Cependant, si je change cela str à format le problème disparaît.L'appel de la fonction str dans l'expression d'une instruction cond provoque une exception ClassCastException

code:

(defn begins-with [chr str] 
    (cond 
    (or (nil? str) (empty? str)) "Hey the string is empty!" 
    (= (first str) chr) (str "found: " chr) 
    :else "Didn't begin with the target char")) 

REPL:

(begins-with \A "") 
=> "Hey the string is empty!" 

(begins-with \A "asdf") 
=> "Didn't begin with the target char" 

(begins-with \A "Apple") 
ClassCastException java.lang.String cannot be cast to clojure.lang.IFn user/begins-with (form-init5132500100026084016.clj:4) 

Cependant, si je remplace le str dans l'expression à un tout format fonctionne sans problème

code mis à jour

(defn begins-with [chr str] 
    (cond 
    (or (nil? str) (empty? str)) "Hey the string is empty!" 
    (= (first str) chr) (format "found: %s" chr) 
    :else "Didn't begin with the target char")) 

REPL:

(begins-with \A "Apple") 
=> "found: A" 

Il fonctionne tout à coup !!

Quelqu'un peut-il expliquer ce comportement? Est-ce que je manque quelque chose d'évident?

Répondre

3

Votre argument est appelé str, ce qui permet d'observer la fonction principale str.

(str "found: " chr) est ainsi évalué comme ("Apple" "found: " \A), ce qui ne fonctionne pas. Renommez votre variable pour le réparer.