Judking
Judking

Reputation: 6371

Whet does it means to append a integer to a list in erlang?

The normal way to do a list appending is via:

10> [1,2,3] ++ [4].
[1,2,3,4]

But after I convert it to the following way, I actually don't get the point what does the result means here:

11> [1,2, 3] ++ 4.  
[1,2,3|4]

Could anyone give me a explanation? Many thanks.

Upvotes: 3

Views: 419

Answers (1)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

The Erlang lists are described in Getting Started with Erlang User's Guide in chapter Sequential Programming and subchapter Lists. The operator | separates a head of the list from a tail. The proper list ends with the empty list. The syntax with , is just syntactic sugar.

1> [1|[2|[3|[]]]].
[1,2,3]

It is like CONS function in Lisp. The list is called improper list if doesn't end with the empty list.

2> [1|[2|[3|4]]]. 
[1,2,3|4]

You made the improper list by appending number instead of a proper list. ([4] is proper list [4|[]].) See my answer to how is a list constructured by the erlang vm? for more details how it works internally in BEAM VM.

Upvotes: 3

Related Questions