简体   繁体   中英

Illegal Argument Exception - Clojure

I have some Clojure code that seems maddeningly simple and yet is throwing an IllegalArgumentException. For reference, the following code shows 4 functions I have been coding. My error lies in the 4th.

"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])))

The fourth function calls the 3rd function until the values xy and z are not equal. The code compiles correctly yet I get the following sequence in the 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)

Only the first expression is really correct, but I'm making the point that I've tried all possible combinations. Can anyone shed some light on this mysterious error? Possibly test it in your own Clojure environment..?

As a side note, shouldn't fun3 stop when x = y = z? It seems to give an infinite sequence now so the if seems superfluous.

As par your comment above you can use below code (Use existing code 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)]))))

You don't really need fun3 and fun4

take-while像map一样工作,它一次从一个集合中获取一个值并检查谓词(即谓词将获得一个参数)。

I'm not sure what you're trying to do but for me (fun3 [10 10 10 1]) evaluates to [10 10 10 1]

Since this is just a plain old vector the first thing that your anonymous function is called with is just the number 10 when it's expecting 3 arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM