List basics in F#

In a previous post I touched on F# lists, now let’s look a little further into the F# lists.

Note: Also check out Lists (F#) for a far more comprehensive view of F# lists

The MSDN documentation states that F# lists are implemented as singly linked lists.

Creating Lists

First off we can create a list using square brackets and semi colon delimiters, for example

let list = ["One"; "Two"; "Three"]

This creates a string list using type inference, i.e.

val list : string list = [“One”; “Two”; “Three”]

Had we wanted we could also create a list with a type hint mirroring this line (note the string list type hint)

let list : string list = ["One"; "Two"; "Three"]

We can also define this list without the semi-colon delimiter, instead using newlines as per

let list = [
   "One"
   "Two"
   "Three"]

We can declare an empty list as follows

let list = []

We can also declare lists using the range operator, for example

let list = ['a' .. 'z']

Whilst we can define a list of data as above, we can also generate the list in the following way

let list = [for i in 'A' .. 'Z' -> i]

Operators

The double colon :: operator takes a left hand argument as a single item and the right hand side as a list and creates a new list which is made up of the left hand argument and then right hand list appended to it. So, for example

let original = [1; 2; 3]
let list = 0 :: original

will result in list being [0; 1; 2; 3]

We can also concatenate lists using the @ operator, for example

let right = [1; 2; 3]
let left = [3; 2; 1]

let combined = left @ right

This results in a new list which looks like [3; 2; 1; 1; 2; 3]