(Deleting/reposting due to an editing error)
As someone mentioned, the functions `prepend` and `append` exist in the
Tupelo library
<https://github.com/cloojure/tupelo#adding-values-to-the-beginning-or-end-of-a-sequence>
to
prevent this kind of confusion:
from the README:
------------------------------------------------------------------------------------
Adding Values to the Beginning or End of a Sequence
Clojure has the cons, conj, and concat functions, but it is not obvious how
they should be used to add a new value to the beginning of a vector or list:
; Add to the end
> (concat [1 2] 3) ;=> IllegalArgumentException
> (cons [1 2] 3) ;=> IllegalArgumentException
> (conj [1 2] 3) ;=> [1 2 3]
> (conj [1 2] 3 4) ;=> [1 2 3 4]
> (conj '(1 2) 3) ;=> (3 1 2) ; oops
> (conj '(1 2) 3 4) ;=> (4 3 1 2) ; oops
; Add to the beginning
> (conj 1 [2 3] ) ;=> ClassCastException
> (concat 1 [2 3] ) ;=> IllegalArgumentException
> (cons 1 [2 3] ) ;=> (1 2 3)
> (cons 1 2 [3 4] ) ;=> ArityException
> (cons 1 '(2 3) ) ;=> (1 2 3)
> (cons 1 2 '(3 4) ) ;=> ArityException
Do you know what conj does when you pass it nil instead of a sequence? It
silently replaces it with an empty list: (conj nil 5) ⇒ (5) This can cause
you to accumulate items in reverse order if you aren’t aware of the default
behavior:
(-> nil
(conj 1)
(conj 2)
(conj 3));=> (3 2 1)
These failures are irritating and unproductive, and the error messages
don’t make it obvious what went wrong. Instead, use the simple prepend and
append functions to add new elements to the beginning or end of a sequence,
respectively:
(append [1 2] 3 ) ;=> [1 2 3 ]
(append [1 2] 3 4) ;=> [1 2 3 4]
(prepend 3 [2 1]) ;=> [ 3 2 1]
(prepend 4 3 [2 1]) ;=> [4 3 2 1]
Both prepend and append always return a vector result.
On Thursday, July 19, 2018 at 8:34:48 AM UTC-7, solussd wrote:
>
> Building off of something Benoit mentioned about conj not being about
> order, but about adding to a collection, consider conj’s behavior when
> adding a map-entry to a hash-map:
>
> (conj (hash-map :a 4 :c 1) [:b 3])
> => {:c 1, :b 3, :a 4}
>
> conj is an interface for adding– not to be conflated with order.
>
>
>
> On Jul 19, 2018, at 10:23 AM, Christian Seberino <[email protected]
> <javascript:>> wrote:
>
> Thanks. I caught that yesterday. Like I said, I'm definitely a beginner.
> ;)
>
>
>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.