Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection of pairs in Clojure using cons

Tags:

java

clojure

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)


(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.

Still I am looking for a good explanation of the error....

like image 883
FredAKA Avatar asked Jan 23 '14 20:01

FredAKA


1 Answers

The problem is that list? check fails on a sequence built with cons as demonstrated below:

(list? (conj () 1)) ;=> true
(list? (cons 1 ())) ; => false

You could switch your call to list? to a call to seq? and it should work.

For details on why this is so I recommend reading this answer: Clojure: cons(seq) vs. conj(list)

like image 111
ponzao Avatar answered Sep 30 '22 09:09

ponzao