2017-10-01 5 views
0

condを設定した場合、一致する分岐の式が(str)になる場合、ClassCastExceptionが返されます。しかし、私がstrformatに変更すると、問題は解消されます。condステートメント内の式のstr関数を呼び出すと、ClassCastExceptionが発生します。

コード:

(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) 

私はformatに表現でstrを交換する場合は、すべてのものは全く問題

更新されたコードを働きません

(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" 

それが突然動作します!!

誰でもこの動作を説明できますか?私は明白な何かを欠いていますか

答えて

3

あなたの引数はstrと呼ばれているので、コアのシャドウイングstr機能です。

(str "found: " chr)は、("Apple" "found: " \A)と評価されていますが、これは機能しません。変数を修正して名前を変更します。

関連する問題