Oops, looks like the end of my message got cut off. Appended below. Alex Osborne wrote: > Dmitri wrote: > > I notice that certain sequence operations such as concat and cons will > > not retain the original type of sequence, for example if you combine > > two vectors together a list will be returned: > > > > user=> (concat [1 2] [3 4]) > > (1 2 3 4) > > > > is this intentional behavior, and would it not be more consistent for > > concat to retain the original type of the data structures, when both > > data structures that were passed in are of the same type. > > It's because concat returns a lazy sequence, the concatenation only > happens when you ask for relevant elements (which has the benefit that > it doesn't need to do any copying, saving both time and memory). If you > want to concatenate two vectors eagerly (so returning another vector) > you could use 'into' instead: > > user=> (into [1 2] [3 4]) > [1 2 3 4] > > > Also, why > > does cons behave differently from conj: > > > > user=> (conj [1 2] 3) > > [1 2 3] > > > > user=> (cons 2 [1 2]) > > (2 1 2) > > Because cons always creates a list (which construct at the front), while > conj "adds" it in the natural (ie fastest) way for that collection type, > vectors "add" at the end. > > user> (conj '(1 2) 3) > (3 1 2) > user> (conj [1 2] 3) > [1 2 3] > user> (conj #{1 2} 3) > #{1 2 3} user> (cons 3 '(1 2)) (3 1 2) user> (cons 3 [1 2]) (3 1 2) user> (cons 3 #{1 2}) (3 1 2)
Usually you'll want to use conj, not cons. Note that when we do (cons 3 [1 2]) cons is making a cons cell that looks like this: +---+---+ | 3 | @-----> (seq [1 2]) +---+---+ It's not converting the whole vector to a list, it just adds the element you cons'd on and points at the existing list. You can see that here: user> (type (cons 3 [1 2])) clojure.lang.Cons user> (type (rest (cons 3 [1 2]))) clojure.lang.APersistentVector$Seq --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---