8

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 should 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)))
foobar
  • 10,854
  • 18
  • 58
  • 66
  • 3
    Just for you to better understand `cons`. `cons` stands for "construct". It constructs list adding new elements to the beginning of the list, one by one. The kind of the function you are looking for should append all elements of one list to another or just concatenate 2 lists. Thus, in Common Lisp it is called `append` and in Clojure, as others have already mentioned here, - `concat`. – ffriend Oct 04 '11 at 18:42

3 Answers3

12

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)
skuro
  • 13,414
  • 1
  • 48
  • 67
5

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.

Community
  • 1
  • 1
5

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)
shark8me
  • 638
  • 8
  • 9