The difference between using cons and not using it to declare/initialize list?

Hey, I’m new to Erlang. Just going through the tutorial and have some questions.

I don’t understand the difference between using cons and not using it to declare/initialize list.
When I declare a list with List = [a, b]. I can pattern match them individually. i.e. [Zero, One, Two...] while if I declare it using cons | like, NewList = [a, [a, b, c]] I can pattern match it with head and tail.

My question is that are those different types. My current understanding is of the former being list, while the later a list with an element and a list of list.

Can anybody point me into the right direction?

Also, what’s the de-facto, if there is one platform to ask this kind of questions. As forum seems too formal for it. I tried IRC on libera, but it doesn’t seem to be active.

This is not using cons, this will result in a list whose first element is a and second element is a list [a,b,c]. [a | [a,b,c]] is how you use cons, and in will result in a list of four elements, a, a, b, and c.

Here is a good article for beginners about lists. This book is where I started so I’d highly recommend it.

Forum and slack


You do not declare lists.
You do not initialise lists.
A list is a value like a number.
You can bind a variable to a list or a number or a process id or anything else, but having done so you cannot change the variable or the list.
You are probably familiar with the idea that
1.0, 1.00, 1.000, 1.0e0, 0.1e1,10.0e-1
are just different ways of writing the SAME number.
In precisely the same way,
[a,b,c], [a|[b,c]], [a|[b|[c]]], [a|[b|[c|]]]
are just different ways of writing the SAME list.
The idea that lists can be written two ways, one showing the pairs and one not, goes all the way back to the Lisp 1.5 programmer’s manual, 1961, and probably a couple of years before that.

Erlang does have a sequence data structure which is NOT made of pairs, where all the elements are directly accessible in one step, and that data structure is TUPLES. [a,b,c] is made of smaller lists (, [c], and [b,c]) but the tuple {a,b,c} is not made of smaller tuples, it’s like an immutable array.


Thanks, I was actually following the book. And being dumb. sorry, the syntax is totally new to me and still trying to get use to it. Thanks for your time anyway :smile:

1 Like