Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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!

like image 577
user1797455 Avatar asked Oct 24 '16 23:10

user1797455


1 Answers

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.
like image 129
amalloy Avatar answered Oct 21 '22 01:10

amalloy