0
目标是对凯撒密码进行轻微修改。 首先移动字符的功能: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) (int \A))) 26) (int \A)))
(and (>= ch (int \a)) (<= ch (int \z))) (char (+ (mod (+ val (- (int ch) (int \a))) 26) (int \a)))
:else c)))
则功能映射最后一个字符串:
(defn move-shift-aux [str shift encode-or-decode]
(map-indexed (fn [idx item] (move-char item shift idx encode-or-decode)) str))
`(move-shift-aux "I should have known..." 1 1)` returns
(\J \space \v \l \t \a \s \l \space \r \l \h \r \space \z \d \f \o \g \. \. \.)
,如果我写的:
(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)
我不明白为什么编译器异常,而它直接申请时正常工作。
哦!是!好,“我应该知道!” – user3166747