# LFE-03 -List and cons

**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.

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


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

```plaintext
lfe> (set (cons initial remaining) '(2 4 6 8 10))
(2 4 6 8 10)
lfe> initial
2
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
1
lfe> e2
2
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
10
lfe> q
20
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
C
lfe> tail
(C++ JAVA)
lfe> (cons 'C# tail)
(C# C++ JAVA)   
```                                                                

  
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695034265996/06e292be-d1af-40dc-b577-f7cf3bc12142.png align="center")  

Code tested on Ubuntu 20.04
