difference between into & concat

1,157 views
Skip to first unread message

DemAS

unread,
Oct 18, 2009, 11:39:48 AM10/18/09
to Clojure
Hi all,

I'm just wondering if there is any difference between 'into' and
'concat' ?

(def x (range 1 100 5))
(def y (range 1 100 10))
(concat x y)
(into x y)

I have found only one difference - the 'concat'-functon sorts resulted
list.

Alex Osborne

unread,
Oct 18, 2009, 12:03:49 PM10/18/09
to clo...@googlegroups.com
DemAS wrote:
> I'm just wondering if there is any difference between 'into' and
> 'concat' ?

There are actually more differences than similarities in my opinion.
For starters, 'concat' can take more than 2 arguments:

(concat [1 2] [3 4] [5 6])
=> (1 2 3 4 5 6)

'into' returns whatever collection type is passed in, so for a vector:

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

or a map:

(into {:a 1} [[:b 2] [:c 3]])
=> {;a 1, :b 2, :c 3}

while 'concat' (being lazy) will always return a lazy seq:

(concat [1 2] [3 4])
=> (1 2 3 4)

(concat {:a 1} [[:b 2] [:c 3]])
=> ([:a 1] [:b 2] [:c 3])

> I have found only one difference - the 'concat'-functon sorts resulted
> list.

Neither of them do any sorting, even in your example with ranges the
output is not sorted.

The difference in the ordering is because concat keeps the seqs (in your
example ranges) ordered:

(concat (range 1 5) (range 11 15))
=> (1 2 3 4 11 12 13 14)

While 'into' just repeatedly applies the 'conj' function, which for a
seq will add each element to the front of the seq, instead of the end,
so the second range appears in reverse in front the first:

(into (range 1 5) (range 11 15))
=> (14 13 12 11 1 2 3 4)

When used on a vector however, 'conj' adds to the end, so we get:

(into (vec (range 1 5)) (range 11 15))
=> [1 2 3 4 11 12 13 14]

Reply all
Reply to author
Forward
0 new messages