Clojure:直接应用或通过函数应用的区别
目的是对凯撒密码稍加修改。 首先是移动角色的函数:Clojure:直接应用或通过函数应用的区别,clojure,Clojure,目的是对凯撒密码稍加修改。 首先是移动角色的函数: (defn move-char [c shift idx encode-or-decode] (let [ch (int c) val (mod (* encode-or-decode (+ shift idx)) 26)] (cond (and (>= ch (int \A)) (<= ch (int \Z))) (char (+ (mod (+ val (- (int ch)
(defn move-char [c shift idx encode-or-decode]
(let [ch (int c) val (mod (* encode-or-decode (+ shift idx)) 26)]
(cond
(and (>= ch (int \A)) (<= ch (int \Z))) (char (+ (mod (+ val (- (int ch) (int \A))) 26) (int \A)))
(and (>= ch (int \a)) (<= ch (int \z))) (char (+ (mod (+ val (- (int ch) (int \a))) 26) (int \a)))
:else c)))
如果我写:
(apply str (move-shift-aux "I should have known..." 1 1))
我得到了我想要的:
"J vltasl rlhr zdfog..."
但如果我定义:
(defn moving-shift [str shift]
(apply str (move-shift-aux str shift 1)))
(moving-shift "I should have known..." 1)
我得到:
CompilerException java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn, compiling:(caesar\core.clj:29:44)
我不明白为什么编译器异常在直接应用时工作正常。您正在使用
str
参数从clojure.core
隐藏str
符号。在移动移位
的范围内,str
指的是“我应该知道…”
,而不是clojure.core/str
,因此当调用apply
函数时,会得到一个ClassCastException
,说明字符串不是函数。
为字符串参数使用其他名称
CompilerException java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn, compiling:(caesar\core.clj:29:44)