开发者

In Clojure, how to cons or conj the elements of a collection but not the collection itself?

cons currently behaves like so:

(cons '(1 2) '(3))
;=> ((1 2) 3)

I would like to achieve:

(magic-cons '(1 2) '(3))
;=> (1 2 3)

I couldn't find a resource for this yet this seems so simple I feel there sho开发者_运维问答uld be a built in function.

Or I just don't know the write words to describe this situation. Either way, please let me know. Thanks!

Edit: Please don't answer with "flatten" :P ie

(flatten (cons '(1 2) '(3)))


You have to use concat:

clojure.core/concat
([] [x] [x y] [x y & zs])
  Returns a lazy seq representing the concatenation of the elements in the supplied colls.

Sample use:

user> (concat '(1 2) '(3))
(1 2 3)


I do believe you are looking for concat (think "concatenate lists"):

[Concat] returns a lazy seq representing the concatenation of the elements in the supplied colls.

In this case the usage would be:

(concat '(1 2) '(3))    

Note that unlike (many) other LISP-dialects, Clojure's concat yields a lazy sequence. See How to covert a lazy sequence to a non-lazy in Clojure? for how to "force" a sequence (this may or may not be useful/needed, depending upon larger context, but is important to keep in mind).

Happy coding.


An alternative is "into".

into always returns the type of the first argument, unlike concat which always returns a list.

=> (into [2 4] '(1 2 3))
[2 4 1 2 3]

(into '(2 4) '(1 2 3))
(3 2 1 2 4)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜