3.3. Lists

3.3.1. Creating a list

The eq languate permit the creation of lists, wich is a collection of expression separated by commas and between []

$ eq eval '[1, 2, 3]'
[ 1, 2, 3 ]

for a list of simple numbers

$ eq eval '[3 * 2, x, y / 2]'
|¯       y ¯| 
| 6, x, --- | 
|_       2 _|

for a list of more complex content.

You also can build a list from the empty list [] and using the cons (or append) operator noted ::

$ eq eval '1 :: 3 :: []'
[ 1, 3 ]

Don’t try to format an expression directly by writing some :: into it, because it won’t be translated to a real list during the formating.

$ eq format '1 :: 3 :: []'
1 :: 3 :: []

3.3.2. General front-appending

You can append any element at the front of an existing list using the cons operator (::)

$ eq eval 'x :: [1, 2, 3]'
[ x, 1, 2, 3 ]

3.3.3. Indexing a list

List can be indexed to get back a specific element of it.

$ eq format '[3 * 2, x, y / 2] _ 2'
|¯         y ¯|     
| 3.2, x, --- |     
|_         2 _|     
                2
$ eq eval '[3 * 2, x, y / 2] _ 2'
x

The indices go from 1 to length of the list (included).

3.3.4. Deconstruction of a list

You can pattern match a list, either directly, or using the :: operator. First let’s look to the exact matching

$ cat docexample/list_matching_full.txt
matchExactList( [1, 2, 3] ) :> perfect;
matchExactList( [a, b, c] ) :> list_of_three;
matchExactList( a )         :> nothing;

matchExactList( [1,4,3] ) + matchExactList( [1,2,3] )
$ eq eval -f docexample/list_matching_full.txt
list_of_three + perfect

It’s really simple, we try to match, the first match is the most precise, the one returning list_of_three accept all list of length three and the last match accept anything. Now we can try to deconstruct a list element by element.

$ cat docexample/ignorefirst.txt
ignoreFirst( x :: xs ) :> xs;

ignoreFirst( [x, y] ) + ignoreFirst( x1 :: x2 :: x3 :: [] )
$ eq eval -f docexample/ignorefirst.txt
[ y ] + [ x2, x3 ]

You can think at the cons matching of a list as if you’ve built your list only with ::. We can also imagine a function which return half of the list, returning only the odd or even elements.

$ cat docexample/list_odds.txt
oddsOfList( x :: y :: xs ) :> x :: oddsOfList( xs );
oddsOfList( [x] ) :> [x];
oddsOfList( []  ) :> [];

oddsOfList( [a, b, d, c, 15, 10, 42 ] )
$ eq eval -f docexample/list_odds.txt
[ a, d, 15, 42 ]

There is more information on list processing in the description of the library’s functions.

Table Of Contents

Previous topic

3.2. Boolean

Next topic

3.4. Variables

This Page