While reading the LearnYouSomeErlang and I found that cons operator is used to get the first element of list. I was a bit confused as to how that works because earlier in the book he mentions that cons operator is used to add elements to the list.
This function returns the first element of a List.
head([H|_]) -> H.
Found in this page http://learnyousomeerlang.com/syntax-in-functions.
Can someone explain how this works in returning the first element of a list.
The cons operator can be used to pattern match a list. So a list can be pattern matched to
[H|T]which deconstructs the list andHis the first element of the list and theTis the remaining items of the list.So, the cons operator is both used for pattern matching and also to construct lists. E.g of construction is
X = [1|[2,3]].