Duong Nhat
Duong Nhat

Reputation: 129

Clojure: how to convert cons to list

(cons 1 (list 2 3)) returns a clojure.lang.cons. How can I convert it to clojure.lang.PersistentList?

Upvotes: 3

Views: 914

Answers (4)

Thumbnail
Thumbnail

Reputation: 13473

Clojure: how to convert cons to list

Don't!

Clojure is built upon extensible abstractions. One of the most important is the sequence.

I can think of no reason why you would want to convert a cons into a listor vice versa. They are both sequences and nothing much else. What you can do with one you can do with the other.


The above takes forward Leetwinski's comment on the question.

Upvotes: 6

coredump
coredump

Reputation: 38799

Instead of calling cons and trying to convert the result, use conj:

(conj (list 2 3) 1)
=> (1 2 3)

(type (conj (list 2 3) 1))
=> clojure.lang.PersistentList

Upvotes: 13

Ivan Grishaev
Ivan Grishaev

Reputation: 1681

The easiest way would be to turn it into a vector. This data type works great in Clojure. In fact, when programming in Clojure, the most of the data is kept either in vectors or maps while lists are used for "code as data" (macro system).

In your case, the solution would be:

user=> (vec (cons 1 (list 2 3)))
[1 2 3]

I don't know such a case where you need a list exactly, not a vector or a seq. Because most of the functions operate on sequences but not strict collection types. The cons type should also work, I believe.

If you really need a list, you may use into function that is to convert collections' types. But please keep in mind that when dealing with a list, the order will be opposite:

user=> (into '() (cons 1 (list 2 3)))
(3 2 1)

So you need to reverse the input data first:

user=> (into '() (reverse (cons 1 (list 2 3))))
(1 2 3)

user=> (type (into '() (reverse (cons 1 (list 2 3)))))
clojure.lang.PersistentList

Upvotes: -2

Taylor Wood
Taylor Wood

Reputation: 16194

You can apply the contents of the returned sequence to the list function:

(apply list (cons 1 (list 2 3)))
=> (1 2 3)
(type *1)
=> clojure.lang.PersistentList

Upvotes: 3

Related Questions