Why the cons car cdr are missing in Clojure
I was playing with Clojure REPL and when I try to use cons car that existed in LISP, get this error.
user=> (take 3 '(1 2 3 4)) (1 2 3) user=> (take 2 '(1 2 3 4)) (1 2) user=> (take 1 '(1 2 3 4)) (1) user=> (car '(1 2 3 4 )) CompilerException java.lang.RuntimeException: Unable to resolve symbol: car in this context, compiling:(NO_SOURCE_PATH:6:1) user=> (cons 1 2) IllegalArgumentException Don't know how to create ISeq from: java.lang.Long clojure.lang.RT.seqFrom (RT.java:505) user=>
Looks like these functions are different in Clojure.
Use cons in Clojure like this will output
user=> (cons 1 2) IllegalArgumentException Don't know how to create ISeq from: java.lang.Long clojure.lang.RT.seqFrom (RT.java:505)
It says that Clojure can not create ISeq from the arguments.
If the second argument is vector or list, then is OK.
user=> (cons 1 [2 3]) (1 2 3)
If the first argument is another vector
user=> (cons [1 2] [3 4]) ([1 2] 3 4)
Other variants
user=> (cons '(1 2) [3 4]) ((1 2) 3 4) user=> (cons '(1 2) '(3 4)) ((1 2) 3 4)
Cons symbol or list of symbol
user=> (cons '(sym) '(3 4)) ((sym) 3 4) user=> (cons 'sym '(3 4)) (sym 3 4)
Let's see the documentation of cons
cons clojure.core (cons x seq) Returns a new seq where x is the first element and seq is the rest.
It indicates the the second argument must be a seq.
And the seq in Clojure has special meaning.
seq is a logical list, and unlike most Lisps where the list is represented by a concrete, 2-slot structure, Clojure uses the ISeq interface to allow many data structures to provide access to their elements as sequences.
In another words, sequence in Clojure is not a concrete data structure but an interface which can be implemented in various ways.
If you really want to do it like LISP
user=> (cons 1 '(2)) (1 2)
Clojure
Clojure Internals