Why is the following 2 expressions that can create a list return different results in Erlang?
> ["A" | []]
// returns ["A"]
> [[] | "A"]
// returns [[], 65]
I was expecting that the second expression returns the same result as the first one. Can anyone explain why is this happening?
To properly understand how this works, keep in mind that all these expressions follow this pattern:
where
headis a single element and tail is another list.Also note that strings are list of characters, that is,
"A"is actually equal to[65].Hence, in the first case, a list whose head is
"A"and whose tail is[]is created and that turns, as expected, into["A"].However, in the second case, the head is
[]and the tail is"A", which is equal to[65]. Therefore, the result is the head element ([]) plus all the elements in the tail (65).