LFE-03 -List and cons

LFE-03 -List and cons


2 min read

Output on Terminal

> (lfe_io:format "hello world~n" ())
lfe_io:format function is use to write output on terminal. It can takes one or two arguments as a lists. The first one is nearly always a list written as a string between " ".
Each ~n is replaced by a new line.
The lfe_io:format function itself returns the atom ok
(lfe_io:format "this outputs one LFE term: ~w~n" '(hello))
This list is printed out as it is , however each ~w is replaced by a argument taken in order from the second list.

lfe> (lfe_io:format "this outputs one LFE term: ~w~n" '(beamvm))
this outputs one LFE term: beamvm
lfe> (lfe_io:format "this takes  two LFE terms: ~w ~w~n" '(beamvm lfe))  
this takes  two LFE terms: beamvm lfe

Lists in LFE are surrounded by "(" and ")".

lfe> (set (cons initial remaining) '(2 4 6 8 10))
(2 4 6 8 10)
lfe> initial
lfe> remaining
(4 6 8 10)

cons is a constructor which can be used as a pattern to match against lists.
set allows you to define variables using patterns.

Using cons you can separate the first element of the list from the rest of list .

If you want to give a literal list you need to quote it with '. It is same as atoms.

Nesting of cons

lfe> (set (cons e1 (cons e2 r)) '(1 2 3 4 5 6 7))
(1 2 3 4 5 6 7)
lfe> e1
lfe> e2
lfe> r
(3 4 5 6 7)

If you try to get more elements from the list than it contains you will get an error.
List with no Element

 lfe> (set (cons p (cons q r)) '(10 20))
(10 20)
lfe> p
lfe> q
lfe> r

It is the special case of the list with no elements ().
cons can be use to "extract" head and tail values of a list while matching.

lfe> (set (cons head tail) (list 'C 'C++ 'JAVA))
(C C++ JAVA)
lfe> head
lfe> tail
(C++ JAVA)
lfe> (cons 'C# tail)
(C# C++ JAVA)

Code tested on Ubuntu 20.04