Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 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 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...