简体   繁体   中英

Cons Operator “|” In Erlang

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 and H is the first element of the list and the T is the remaining items of the list.

So, the cons operator is both used for pattern matching and also to construct lists. Eg of construction is X = [1|[2,3]] .

I'm not sure if this will be useful, but...

A cons cell describes a pair of which the first element is a term of some sort and the second is a pointer to another cons cell (or null if at the end of a list). So, if you will let me use '->' as a pointer symbol, a simple cons cell representing a list of one element could be,

[1, -> null] = the list [1]. 

[2, -> [1,-> null]] = the list [2,1], etc.

A list can be thought of as a linked list of cons cells where the 2nd element of the Cons cell is the pointer to the next link.

A Cons operator creates a new list by creating a Cons cell of which the first element is a new list element and the second element is a pointer to the first Cons cell of the original list. The first element is the Head, and the second element (the Tail) is a pointer to next Cons cell in the 'chain'. In Erlang, the above can be written as

[2|[1|[]]]

which is the list [2,1]. As a short-hand, [1|[]] is written as [1], so

 [2|[1|[]]] = [2|[1]]=[2,1]

Now, if my list were [1,2,3], I could represent it as its head Cons-ed with its Tail as in,

[1|[2,3] 

So, because Erlang is awesome, this pattern is available to match on as in: "I have a list, [1,2,3] which can be described as a Cons-ed Hd and a Tail (a pointer to the Hd of the rest of the list). So

[Hd|Tail] = [1,2,3] 

gives

Hd = 1 

and

Tail = [2,->[3,->null]] = [2|[3|[]]] = [2|[3]] = [2,3].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM