[英]Collection of pairs in Clojure using cons
I was writing a Sieve-type function in Clojure based on Sieve of Eratosthenes.....and came across an error with lists of pairs: ClassCastException clojure.lang.Cons cannot be cast to java.lang.Number clojure.lang.Numbers.remainder (Numbers.java:171) 我正在基于Eratosthenes的Sieve在Clojure中编写一个Sieve类型的函数.....并且遇到了对列表的错误:ClassCastException clojure.lang.Cons无法强制转换为java.lang.Number clojure.lang.Numbers .remainder(Numbers.java:171)
(defn mark-true [n]
(cons n '(true)))
(defn unmarked? [ns]
(not (list? ns)))
(defn divides? [m n]
(if (= (mod n m) 0)
true
false ))
(defn mark-divisors [n ns]
(cond
(empty? ns) '()
(and (unmarked? (first ns)) (divides? n (first ns)))
(cons (cons (first ns) '(false)) (mark-divisors n (rest ns)))
:else (cons (first ns) (mark-divisors n (rest ns)))))
(defn eratosthenes [ns]
(cond
(empty? ns) '()
(unmarked? (first ns))
(cons (mark-true (first ns))
(eratosthenes (mark-divisors (first ns) (rest ns))))
:else (cons (first ns) (eratosthenes (rest ns)))))
;(eratosthenes (list 2 3 4 5 6))
;=> ClassCastException clojure.lang.Cons cannot be cast to java.lang.Number clojure.lang.Numbers.remainder (Numbers.java:171)
However, changing the marking style, giving up on cons and using conj or vector pairs instead, both solved the error. 但是,改变标记样式,放弃缺点并使用conj或vector对,都解决了错误。
Still I am looking for a good explanation of the error.... 我仍然在寻找错误的一个很好的解释....
The problem is that list?
问题是
list?
check fails on a sequence built with cons
as demonstrated below: 使用
cons
构建的序列检查失败,如下所示:
(list? (conj () 1)) ;=> true
(list? (cons 1 ())) ; => false
You could switch your call to list?
你可以把你的电话转到
list?
to a call to seq?
打电话给
seq?
and it should work. 它应该工作。
For details on why this is so I recommend reading this answer: Clojure: cons(seq) vs. conj(list) 有关为什么会这样的详细信息,我建议您阅读以下答案: Clojure:cons(seq)vs conj(list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.