非法论证异常 - Clojure

时间:2011-11-15 03:14:22

标签: exception parameters clojure anonymous-function

我有一些Clojure代码看起来非常简单但却抛出了IllegalArgumentException。作为参考,以下代码显示了我编码的4个函数。我的错误在于第4个。

"Determine candy amount for first parameter. Returns even integers only (odd #'s rounded up)."
(defn fun1 [x y] (if (= (rem (+ (quot x 2) (quot y 2)) 2) 1) (+ (+ (quot x 2) (quot y 2)) 1) (+ (quot x 2) (quot y 2))))

"Play one round. Returns vector with new values."
(defn fun2 [[x y z t]] (vector (fun1 x z) (fun1 y x) (fun1 z y) (+ t 1)))

"Yield infinite sequence of turns."
(defn fun3 [[x y z t]] (if (= x y z) (vector x y z t) (iterate fun2 [x y z t])))

(defn fun4 [[x y z t]] (take-while #(not= %1 %2 %3) (fun3 [x y z t])))

第四个函数调用第三个函数,直到值x y和z不相等。代码编译正确但我在REPL中得到以下序列:

Clojure 1.1.0
user=> (load-file "ass8.clj")
#'user/fun4
user=> (fun4 [10 10 10 1])
java.lang.IllegalArgumentException: Wrong number of args passed to: user$fun4--21$fn
(user=> (fun4 [[10 10 10 1]])
java.lang.IllegalArgumentException: Wrong number of args passed to: user$fun4--21$fn
(user=> (fun4 10 10 10 1)
java.lang.IllegalArgumentException: Wrong number of args passed to: user$fun4 (NO_SOURCE_FILE:0)

只有第一个表达式才是真正正确的,但我明确指出我已尝试过所有可能的组合。任何人都可以对这个神秘的错误有所了解吗?可能在你自己的Clojure环境中测试它。?

作为旁注,当x = y = z时,不应该停止fun3吗?它似乎现在给出一个无限的序列,所以if似乎是多余的。

3 个答案:

答案 0 :(得分:1)

与上面的评论相同,您可以使用以下代码(使用现有代码for fun1)

(defn fun2 [v] 
        (loop [[a b c d] v] 
              (if (= a b c) 
                  [a b c d] 
              (recur [(fun1 a c) (fun1 b a) (fun1 c b) (+ d 1)]))))

你真的不需要fun3和fun4

答案 1 :(得分:1)

take-while的工作方式与map类似,它一次从一个集合中获取一个值并检查谓词(即谓词将获得一个参数)。

答案 2 :(得分:0)

我不确定你要做什么,但对我来说(fun3 [10 10 10 1])评估为[10 10 10 1]

因为这只是一个普通的旧向量,所以调用你的匿名函数的第一件事就是当它期望3个参数时的数字10。

相关问题