How to remember the difference between conj and cons in Clojure
When I started writing Clojure, I couldn’t memorize the difference between
conj
and cons
and always used one instead of the another. Their name are
similar, but cons
is used to add an element at the beginning of a vector,
while conj
is used to add an element at the end of it. How can one memorize
this? I found a mnemonic trick over the time that helps me remember this. Here
is it:
The trick is to look at the last letter of each function, s
and j
. As shown
in the image below, the s
of cons
shows the right, while the j
of
conj
shows the left.
This means that cons
pushes elements from the left to the right, that is,
at the beginning of a vector. conj
, on the other hand, pushes elements
from the right to the left, which is at the end of a vector. That’s it.
Once you see this in your head, you’ll never forget the difference between
cons
and conj
on a vector.