F# Lists

F# lists can be defined as collections of ordered values that have the same type and are of the same order.

F# list is an immutable object, which means that it cannot be modified once it has been created.

Operations on lists, on the other hand, return a new list that has the changes that were requested.

There are many functions available for creating, manipulating, and querying lists in F#, which makes them powerful and flexible.

A sequence of data, such as a list of names, numbers, or other values, can be represented by them.

There is a F# module named Microsoft.FSharp.Collections.List which has all of the common operations on lists. However, F# automatically imports this module into every F# application and makes it accessible to every single application written with F#.

By end of article you will learn how to create and manipulate F# lists of items, including how to insert and remove items, filter and sort lists, and perform operations on more than one list at a time.



F# Lists Creation Methods

Here are some of the ways in which you can create a list:

MethodsOverview
LiteralsBy using list literals, we can create a list.
(::)By using the cons (::) operator, you can achieve this.
List.initThe List module has a List.init method that can be used to start a list.
syntactic constructBy utilizing a syntactic construct called List Comprehension.

List Literals

The list literal expresses a new list that will contain the values specified in the list literal expression.

List literals in F# are displayed as follows:

let list1 = [1; 2; 3; 4]
let list2= ["apple"; "banana"; "cherry"]

The Cons (::) Operator

A new list can be created by prepending an element to an existing list using the cons operator :: in F#.

It is the shorthand form of the word “construct” and is pronounced as “cons“.

:: accepts two operands: an element and a list.

An element is returned as part of a new list, which consists of the element and the elements from the original list that follow.

Here’s an example.

let list1 = 1 :: [2; 3; 4]
let list2 = 1::2::3::4::5::6::7::8::9::10::[];;

The [] character denotes that the list is empty.


List Init Method

Using the List.init method in F# is a way of creating a new list by applying a given function to the integers in a given range of values.

Here is what the syntax of List.init looks like:

val init : int -> (int -> 'T) -> 'T list

Firstly, there is an argument specifying the number of items to generate in the new list, and secondly there is an argument specifying the initializer function that is used to create the list’s items.

let stringList = List.init 5 (fun i -> "Item " + string i)

Here, String i function is used here to generate a list of strings.


List Comprehensions

A F# list comprehension is a concise method to create additional lists of data from an existing sequence or list. The concept of list comprehension is based on the mathematical notation of set comprehension and can be used to map, combine, and filter elements.

For example,

let list1 = [1 .. 10]

There is a construct in generators which is: [for x in a collection do … yield expr],

For example,

let evenNumbers = [ for i in 1..10 do if i % 2 = 0 then yield i ]

In the same way that the yield keyword pushes some individual value into a list, yield! Is used to push a collection of values into the list.

Below is an example function demonstrating how the methods above can be used:

Example: 

The output of the example above is as follows:

The list: [1; 2; 3; 4; 5; 6; 7; 8]
The list: [1; 2; 3; 4; 5; 6]
The list: [1; 2; 3; 4; 5; 6; 7; 8]
The list: [a; b; c; d; e; f; g; h]
The list: [0,0,0; 1,1,1; 2,4,8; 3,9,27; 4,16,64]
The list: [1; 4; 9; 16; 25; 36; 49; 64]
The list: [15; 30; 45; 60; 75; 90]
The list: [1; 2; 3; 2; 3; 4]

F# List Data Type

Below is a table that shows a variety of properties associated with list data types:

PropertyTypeOverview
HeadTThis is the first element of the list.
EmptyT listAn empty list of the appropriate type can be returned by this static property as a result of the request.
IsEmptyboolIt is true if there are no elements in the list.
ItemTThis element is at the index specified (zero-based).
LengthintElement count.
TailT listA list that does not contain the first element.

Here is an example of how these properties can be used:

Example: 

let li = [ 1; 3; 5; 7; 9; 11; 13; 15 ]// Use of Properties printfn "li.IsEmpty is %b" (li.IsEmpty) printfn "li.Length is %d" (li.Length) printfn "li.Head is %d" (li.Head) printfn "li.Tail.Head is %d" (li.Tail.Head) printfn "li.Tail.Tail.Head is %d" (li.Tail.Tail.Head) printfn "li.Item(1) is %d" (li.Item(1))

The results of all the above properties are printed as follows:

li.IsEmpty is false
li.Length is 8
li.Head is 1
li.Tail.Head is 3
li.Tail.Tail.Head is 5
li.Item(1) is 3

F# Lists Basic Operators

There are several basic operations you can perform on a list data type, as illustrated in the following table:

ValueOverview
append : ‘T list → ‘T list → ‘T listThe function returns a new list containing the elements of the first list followed by the elements of the second list at the end.
average: ‘T list → ‘T list → ‘T listThe average element in the list of elements is returned as the result of this function.
averageBy : (‘T → ^U) → ‘T list → ^UBy applying the function to each element of the list and taking the average of both elements, it will return the average of the elements generated.
choose : (‘T → ‘U option) → ‘T list → ‘U listThe given function will be applied to every element of the list one by one. This function will return a list of each element’s result for each element where the function returns Some as a result.
Collect : (‘T → ‘U list) → ‘T list → ‘U listThis function will be applied to each element of the list, one at a time. Return the combined list of all the results after concatenating all of them together.
concat : seq<‘T list> → ‘T listA new list will be returned which will contain the elements of all of the lists, sorted alphabetically.
empty : ‘T listThe function returns an empty list with the given type as its value.
exists : (‘T → bool) → ‘T list → boolThe function checks if any element from the list meets the given predicate by checking whether it is present.
exists2 : (‘T1 → ‘T2 → bool) → ‘T1 list → ‘T2 list → boolIn this function, it is tested to see if a pair of corresponding elements in the lists is satisfied by the given predicate.
filter : (‘T → bool) → ‘T list → ‘T listIn this function, a new collection is returned that contains only those elements of the original collection for which the given predicate corresponds to true.
find : (‘T → bool) → ‘T list → ‘TIt returns the element that is the first element to return true when the given function is used.
findIndex : (‘T → bool) → ‘T list → intA predicate that is satisfied by the first element in the list is returned.
fold : (‘State → ‘T → ‘State) → ‘State → ‘T list → ‘StateThis function threads an accumulator argument through each element of the collection. It applies the function to the second argument and the first element of the list. This result will then be passed by the program along with the second element, and the process will continue in this way. It then returns the final result. A function f is given, and the elements are i0…iN, so this function computes f (… (f s i0) i1 …) iN.
fold2 : (‘State → ‘T1 → ‘T2 → ‘State) → ‘State → ‘T1 list → ‘T2 list → ‘StateThis function applies a function to the elements of two collections that correspond to each other, and threads an accumulator argument through the computation as well. There must be identical collections. Using i0…iN and j0…jN as input functions, this function computes f (… (f s i0 j0)…) iN jN.
foldBack : (‘T → ‘State → ‘State) → ‘T list → ‘State → ‘StateThis function applies a function to every element in the collection, through which an accumulator argument is passed through the computation for each element. A function f is passed as an input, and the input elements i0…iN are passed as input which computes f i0 (…(f iN s)).
foldBack2 : (‘T1 → ‘T2 → ‘State → ‘State) → ‘T1 list → ‘T2 list → ‘State → ‘StateIn this function, an element of two collections is threaded through the computation and a function reference is passed as an argument. Collections must be identical. A function f is passed to this function and if the elements in each case are i0…iN and j0…jN, then this function will compute the value of f i0 j0 (…(f iN jN s )).
forall : (‘T → bool) → ‘T list → boolThis function checks if all elements satisfy the given predicate in the collection.
forall : (‘T → bool) → ‘T list → boolIdentifies whether all elements corresponding to the given predicate are satisfied pairwise in the collection.
head : ‘T list → ‘TIt is used to return the first element in a list.
init : int → (int → ‘T) → ‘T listThe function creates a list by using the given generator as an index on each item in the list.
isEmpty : ‘T list → boolThis method returns true if the list does not contain any elements, and false if it does.
iter : (‘T → unit) → ‘T list → unitEvery element in the collection will be applied with the given function.
iter2 : (‘T1 → ‘T2 → unit) → ‘T1 list → ‘T2 list → unitThe given function is applied simultaneously to two collections. There must be an identical size between the two collections.
iteri : (int → ‘T → unit) → ‘T list → unitEach element in the collection is applied to the given function. Integers passed to the function indicate element indexes.
iteri2 : (int → ‘T1 → ‘T2 → unit) → ‘T1 list → ‘T2 list → unitThe given function will be applied simultaneously to two collections. There must be an equal size between the two collections. This integer indicates the index of the element that has been passed to the function.
length : ‘T list → intThe length of the list is returned by this function.
map : (‘T → ‘U) → ‘T list → ‘U listIn this method, the elements of a collection are the results of applying a given function to each element of a collection, and the result is returned as the elements of a new collection.
map2 : (‘T1 → ‘T2 → ‘U) → ‘T1 list → ‘T2 list → ‘U listIn this method, a new collection is created whose elements correspond to the respective elements of the two sets of collections if the given function is applied pairwise to the corresponding elements of the two sets.
map3 : (‘T1 → ‘T2 → ‘T3 → ‘U) → ‘T1 list → ‘T2 list → ‘T3 list → ‘U listIn this function, the three collections are applied simultaneously to their corresponding elements to produce a new collection.
mapi : (int → ‘T → ‘U) → ‘T list → ‘U listApplying a given function to each element of the collection creates a new collection whose elements are the results of the application. This integer index represents the element’s index (from 0) when passed to the function.
mapi2 : (int → ‘T1 → ‘T2 → ‘U) → ‘T1 list → ‘T2 list → ‘U listThis is similar to List.mapi, but it maps the elements of two lists with the same length to each other.
max : ‘T list → ‘TBy using Operators.max, this function returns the greatest value among all of the elements in the list.
maxBy : (‘T → ‘U) → ‘T list → ‘TThe function returns the greatest element in the list among all the elements of the list, comparing the result of the function with its Operators.max method.
min : ‘T list → ‘TThis function returns the lowest element in a list, compared using Operators.min as a comparison method.
minBy : (‘T → ‘U) → ‘T list → ‘TUsing Operators.min on the result of the function, this function returns the lowest element within all the elements of the list
nth : ‘T list → int → ‘TThe index of each item in the list. 0 is the index of the first element in the list.
ofArray : ‘T [] → ‘T listFrom an array of items, a list can be created.
ofSeq : seq<‘T> → ‘T listProvides a new list based on the enumerable object given to it.
partition : (‘T → bool) → ‘T list * ‘T listThis method splits a collection into two collections containing elements that return true or false based on the given predicate.
permute : (int → int) → ‘T list → ‘T listSpecifies a permutation method that returns a list with all elements permuted.
pick : (‘T → ‘U option) → ‘T list → ‘UReturns the first result when the given function returns Some for some value when applied to successive elements.
reduce : (‘T → ‘T → ‘T) → ‘T list → ‘TThis function is applied to each element of the collection, and an accumulator argument is passed to the function when the computation is performed. The first two elements of the list are subjected to the specified function. The result is then passed into the function with the third element and so on. Lastly, it returns the final result. Suppose that the input function is f and the input elements are i0…iN, then the function will compute f (… (f i0 i1) i2 …) iN for the specified input function.
reduceBack : (‘T → ‘T → ‘T) → ‘T list → ‘TThe function is applied to each element of the collection, and then an accumulator argument is passed through the computation to control the operation. A function f is inputted, and the elements will be i0…iN, then the function will calculate f i0 (…(f iN-1 iN)).
replicate : (int → ‘T → ‘T list)The function creates a list by using the given generator as an index on each item in the list.
rev : ‘T list → ‘T listThere is a function that returns a new list that has the elements in reversed order.
scan : (‘State → ‘T → ‘State) → ‘State → ‘T list → ‘State listA function is applied to each element of the collection, threading the computation through the accumulator argument associated with each element. With this function, we can take the second argument and apply the function specified to it along with the first element of the list. Following this, the result of the calculation is passed into the function along with the second element, and so on. At the end, it returns both the intermediate and final results.
scanBack : (‘T → ‘State → ‘State) → ‘T list → ‘State → ‘State listThe result is both the intermediate and final results, just like foldBack.
sort : ‘T list → ‘T listBy using Operators.compare, this function sorts the list given to it.
sortBy : (‘T → ‘Key) → ‘T list → ‘T listThe given list is sorted using the keys provided by the projection given in the input. Using the Operators.compare method, keys are compared between each other.
sortWith : (‘T → ‘T → int) → ‘T list → ‘T listThis function uses the comparison function provided in the given list to sort the given list.
sum : ^T list → ^TCalculates the sum of elements in a list.
sumBy : (‘T → ^U) → ‘T list → ^UEach list element’s result is returned as a sum when the function is applied.
tail : ‘T list → ‘T listA list of input elements without the first element is returned.
toArray : ‘T list → ‘T []The function creates an array from a list given to it.
toSeq : ‘T list → seq<‘T>Provides a sequence view of the given list.
tryFind : (‘T → bool) → ‘T list → ‘T optionProvides a list of elements for which a function returns true based on the given parameters. If there is no such element, the return value will be None.
tryFindIndex : (‘T → bool) → ‘T list → int optionThere will be an index returned that represents the position in the list of the first element that meets the given predicate. If there is no such element, then return None.
tryPick : (‘T → ‘U option) → ‘T list → ‘U optionAs we apply successive elements to the given function, it returns a first result when the function returns Some for a certain value. The return value should be None if such an element does not exist.
unzip : (‘T1 * ‘T2) list → ‘T1 list * ‘T2 listThis function is used to split a list of pairs into two lists.
unzip3 : (‘T1 * ‘T2 * ‘T3) list → ‘T1 list * ‘T2 list * ‘T3 listThe function splits a list of triples into three separate lists.
zip : ‘T1 list → ‘T2 list → (‘T1 * ‘T2) listThis function is used to combine the two lists into a list of pairs. There must be an equal length between the two lists.
zip3 : ‘T1 list → ‘T2 list → ‘T3 list → (‘T1 * ‘T2 * ‘T3) listA list of triples is formed by combining the three lists. There must be an equal length between the lists.

F# Lists Reversing

Here is a program that shows how to reverse a list recursively:

Example: 

let li = [ 1; 3; 5; 7; 9; 11; 13; 15 ] printfn "The original list: %A" lilet reverse lst = let rec loop acc = function | [] -> acc | hd :: tl -> loop (hd :: acc) tl loop [] lstprintfn "The reversed list: %A" (reverse li)

And the output will be:
F# Lists Reversing
If you need to do the same thing, you could use the List.rev function of the module as follows:

Example: 

let li = [ 1; 3; 5; 7; 9; 11; 13; 15 ] printfn "The original list: %A" li printfn "The reversed list: %A" (List.rev li)

Output:

F# Lists Reverse output


F# List.average

Below is an example of calculating the average of all elements in the list by using List.average:

Example: 

let numbers = [5.0; 2.0; 22.0; 1.0; 12.0] let average = List.average numbers printfn "The average of the numbers is: %f" average

And the result is:

F# List average


F# List Filter

In the following program, you will be able to see how to filter a list using the List.filter method.

Example: 

let li1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] printfn "The list: %A" li1 let li2 = li1 |> List.filter (fun x -> x % 2 = 1);; printfn "Filtered Odd Value from the list are: %A" li2

Filtering results of the list are as follows:

F# List Filter


F# List Map

The List.map method is used to map a list between two types:

Example: 

let li1 = [1; 2; 3; 4; 5] printfn "The list: %A" li1 let li2 = li1 |> List.map (fun x -> (x * x).ToString());; printfn "The Mapped list: %A" li2

Mapping the list into different types outputs as follows:

F# List Map


F# List Sorting

Lists can be sorted by using the List.sort method.

Example: 

let li = [5; 0; 45; -6; 12; 8; 1; -8] printfn "The list: %A" lilet li_sort = List.sort li printfn "The sorted list: %A" li_sort

As a result of sorting the list, here is what the output will look like:

F# List Sorting


F# List Append

List.append is a method that combines two lists and appends them to each other:

Example: 

let li1 = [2; 4; 58; 85; 12 ] let li2 = [6; 5; 4; 3; 2] let li_append = List.append li1 li2printfn "The first list: %A" li1 printfn "The second list: %A" li2 printfn "The appened list: %A" li_append

The output will be as follows:

The first list: [2; 4; 58; 85; 12]
The second list: [6; 5; 4; 3; 2]
The appened list: [2; 4; 58; 85; 12; 6; 5; 4; 3; 2]

F# List.Sum

List.sum is a method that returns the sum of the elements in a list

Example: 

let li = [2; 4; 58; 85; 12 ] let sum = List.sum li printfn "The sum: %d" sum

The sum of all elements is:

The sum: 161

F# List.Fold

In the List.fold method, a function is applied from left to right to each element of the List:

Example: 

let numbers = [2; 1; 5; 6; 8] let sum = List.fold (fun acc x -> acc + x) 2 numbers printfn "The sum of the numbers is: %d" sum

The output will be as follows:

F# List Fold

Example Explanation

This F# code defines a list of integers numbers with the values [2; 1; 5; 6; 8]. It then uses the List.fold function to calculate the sum of the elements in the list, which is stored in the variable sum. The initial value of the accumulator acc is set to 2.

The List.fold function takes three arguments: a function that specifies how to combine the accumulator with each element of the list, an initial value for the accumulator, and the list itself.

In this case, the lambda function passed as the first argument to List.fold takes two arguments: acc and x. It returns the sum of acc and x, which is used as the new accumulator value. The accumulator’s initial value is 2.

The List.fold function applies the lambda function to each list element and updates the accumulator accordingly. It starts with an initial accumulator value of 2, and then adds 2 to each element in the list, resulting in a final accumulator value of 2 + 2 + 1 + 5 + 6 + 8, which is 24.

Finally, the code uses the printfn function to print out the results. This program would output:

The sum of the numbers is: 24

If you liked this article and found it informative regarding F# functional programming language, you can leave your feedback by reacting below.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *