/ erlang

Erlang Data Structures : Lists

  • A List can contain element of any type.
  • lists module provide functions that operate on Lists.
  • Lists are of the form [1,2,3,im_an_atom,"random_string",{person,"Adarsh"}].
  • You can add two list using ++ and subtract one list from another using --
1> A=[1,2,3].
[1,2,3]
2> B=[4,5,6].
[4,5,6]
3> A++B.
[1,2,3,4,5,6]
4> C=[1,2,3,4].
[1,2,3,4]
5> C--[4,5].
[1,2,3
  • Cons (Construct) operator | is used to Construct a new list.
  • Cons also split head of the list (first element) from the tail list (all the remaining elements).
1> [H|T]=[1,2,3,im_an_atom,"random_string",{person,"Adarsh"}].
[1,2,3,im_an_atom,"random_string",{person,"Adarsh"}]
2> H.
1
3> T.
[2,3,im_an_atom,"random_string",{person,"Adarsh"}]
4> [H|T]=[1,2,3,im_an_atom,"random_string",{person,"Adarsh"}].
[1,2,3,im_an_atom,"random_string",{person,"Adarsh"}]
5> [{person,"Joe"}| T].                                       
[{person,"Joe"},
 2,3,im_an_atom,"random_string",
 {person,"Adarsh"}]
  • tl() and hd() bif can also be used to access head and tail of the list.
1> L=[1,2,3,im_an_atom,"random_string",{person,"Adarsh"}].    
[1,2,3,im_an_atom,"random_string",{person,"Adarsh"}]
2> hd(L).
1
3> tl(L).
[2,3,im_an_atom,"random_string",{person,"Adarsh"}]

length/1

length/1 traverse through all elements to find length.

length/1 is not a constant time operation and when used on a list with a lot of elements can affect performance a bit. But its implemented in C code its not that bad as well. If all you want to ensure is the list is not empty using pattern matching is better.

%Bad Bad
my_fun(MyList) when length(MyList) > 0 -> 
....

%Insted use the below as only if elements are present it will match.
my_fun([H|Tail]) -> 
....

Properlist

A list of form [Elem | []] is called a properlist. Meaning the tail is an empty list.

When iterating over a properlist we can match againstr [] to know we have reached end of list. And some standard function in erlang fail if passed a im-proper list.

1> length([1,2,3]).        
3
2> length([1|3]).  
** exception error: bad argument
     in function  length/1
        called as length([1|3])
3> length([1|[3|[]]]).
2

Read this next.

References

Erlang Programming
Erlang Docs