Clojure has its own collections, and has no need of the traditional lispy cons cells. But I find the concept interesting, and it is used in some teaching materials (e.g., SICP). I have been wondering if there is any reasons that this cons primitive needs to be a primitive. Can't we just implement it (and the traditional functions that operate on it) in a library? I searched, but I found no such library already written.
Of course, you can implement cons cells with no tools other than lambda
(called fn
in Clojure).
(defn cons' [a d]
(fn [f] (f a d)))
(defn car' [c]
(c (fn [a d] a)))
(defn cdr' [c]
(c (fn [a d] d)))
user> (car' (cdr' (cons' 1 (cons' 2 nil))))
2
This is as space-efficient as you can get in Clojure (a lambda closing over two bindings is just an object with two fields). car
and cdr
could obviously be more time-efficient if you used a record or something instead; the point I'm making is that yes, of course you can make cons cells, even if you have next to no tools available.
Why isn't it done, though? We already have better tools available. Clojure's sequence abstraction makes a better list than cons cells do, and vectors are a perfectly fine tuple. There's just no great need for cons cells. Combine that with the fact that anyone who does want them will find it trivially easy to implement anew, and there are no customers for a prospective library solution.