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

时光毁灭记忆、已成空白 提交于 2019-12-28 04:31:49

问题


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!


回答1:


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.


来源:https://stackoverflow.com/questions/40229259/wrong-number-of-args-0-passed-to-persistentvector-on-loop-recur-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!