# Lists

## Syntax

• [] // an empty list.

head::tail // a construction cell holding an element, head, and a list, tail. :: is called the Cons operator.

let list1 = [ 1; 2; 3 ] // Note the usage of a semicolon.

let list2 = 0 :: list1 // result is [ 0; 1; 2; 3 ]

let list3 = list1 @ list2 // result is [ 1; 2; 3; 0; 1; 2; 3 ]. @ is the append operator.

let list4 = [ 1..3 ] // result is [ 1; 2; 3 ]

let list5 = [ 1..2..10 ] // result is [ 1; 3; 5; 7; 9 ]

let list6 = [ for i in 1..10 do if i % 2 = 1 then yield i ] // result is [ 1; 3; 5; 7; 9 ]

## Calculating the total sum of numbers in a list

By recursion

The above example says: "Look at the `list`, is it empty? return 0. Otherwise it is a non-empty list. So it could be ``, `[1; 2]`, [1; 2; 3] etc. If `list`is  then bind the variable `head` to `1` and `tail` to `[]` then execute `head + sumTotal tail`.

Example execution:

A more general way to encapsulate the above pattern is by using functional folds! `sumTotal` becomes this:

## Creating lists

A way to create a list is to place elements in two square brackets, separated by semicolons. The elements must have the same type.

Example:

When a list has no element, it is empty. An empty list can be declared as follows:

Other example

To create a list of byte, simply to cast the integers:

It is also possible to define lists of functions, of elements of a type defined previously, of objects of a class, etc.

Example

Ranges

For certain types of elements (int, float, char,...), it is possible to define a list by the start element and the end element, using the following template:

`[start..end]`

Examples:

You can also specify a step for certain types, with the following model:

`[start..step..end]`

Examples:

Generator

Another way to create a list is to generate it automatically by using generator.

We can use one of the following models:

`[for <identifier> in range -> expr]`

or

`[for <identifier> in range do ... yield expr]`

Examples

Operators

Some operators may be used to construct lists:

Cons operator ::

This operator :: is used to add a head element to a list:

Concatenation

The concatenation of lists is carried out with the operator @.