Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

clojure - Wrong number of args (0) passed to: PersistentVector on loop/recur function

Trying to define a factors function that will return a vector of all the factors of a number using loop/recur.

;; `prime?` borrowed from https://swizec.com/blog/comparing-clojure-and-node-js-for-speed/swizec/1593

(defn prime? [n]
  (if (even? n) false
      (let [root (num (int (Math/sqrt n)))]
        (loop [i 3] (if (> i root) true
                        (if (zero? (mod n i)) false
                            (recur (+ i 2))))))))

(defn factors [x] (
  (loop [n x i 2 acc []]
    (if (prime? n) (conj acc n)
        (if (zero? (mod n i)) (recur (/ n i) 2 (conj acc i))
            (recur n (inc i) acc))))))

But I keep running into the following error:

ArityException Wrong number of args (0) passed to: PersistentVector clojure.lang.AFn.throwArity

I must be missing something obvious here. Any suggestions are much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let me move the whitespace in your code so it's obvious to you what is wrong:

(defn factors [x] 
  ((loop [n x i 2 acc []]
     (if (prime? n) (conj acc n)
         (if (zero? (mod n i)) (recur (/ n i) 2 (conj acc i))
             (recur n (inc i) acc))))))

You see that weird (( at the start of your function? What's that all about? Remember that in Clojure, as in lisps in general, parentheses are not a grouping construct! They are a function-call mechanism, and you can't just throw extras in for fun. Here, what you wrote has the following meaning:

  1. Run this loop that will compute a vector.
  2. Call the resulting value as a function, passing it no arguments.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...