错误数量的参数 (0) 传递给:循环/重复函数上的 PersistentVector [英] Wrong number of args (0) passed to: PersistentVector on loop/recur function
问题描述
尝试定义一个 factors
函数,该函数将使用 loop/recur 返回一个数字的所有因子的向量.
<代码>;;`prime?` 借自 https://swizec.com/blog/comparing-clojure-and-node-js-for-speed/swizec/1593(定义素数?[n](如果(甚至?n)假(让 [root (num (int (Math/sqrt n)))](loop [i 3] (if (> i root) true(如果(零?(mod n i))假(重复 (+ i 2)))))))))(定义因子 [x] ((循环 [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))))))
但我一直遇到以下错误:
ArityException 错误数量的 args (0) 传递给:PersistentVector clojure.lang.AFn.throwArity
我一定在这里遗漏了一些明显的东西.非常感谢任何建议!
让我移动你代码中的空格,这样你就可以明显看出哪里出了问题:
(定义因子 [x]((循环 [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))))))
你在函数的开头看到了奇怪的 ((
?那是什么?记住在 Clojure 中,就像在一般的 lisps 中一样,括号不是分组结构!它们是一个函数调用机制,你不能随便乱加东西.这里,你写的意思如下:
- 运行这个
loop
来计算一个向量. - 将结果值作为函数调用,不传递参数.
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!
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:
- Run this
loop
that will compute a vector.- Call the resulting value as a function, passing it no arguments.
这篇关于错误数量的参数 (0) 传递给:循环/重复函数上的 PersistentVector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!