Creating lists in F#
February 19, 2017 Leave a comment
Lists in F# are type safe and immutable. Type safety means that all elements in the list must be of the same type. Immutability implies that once the list is created we cannot add new elements to it. Instead, a new list will be created with the elements of the old list copied to the new list along with the new value(s) we want to add to it.
Here’s how to declare an empty list:
let myFirstList = [];
The ‘::’ operator is used to add a new item to the head of the list:
let stringList = "some string entry" :: myFirstList
Note how we must declare a new list to store the extended list. Only writing…
"some string entry" :: myFirstList
…won’t do anything to “myFirstList” and the F# compiler will emit a warning that the return value of the operation was ignored.
Let’s add one more string:
let newStringList = "another string entry" :: stringList
Here are our lists in the F# interactive window:
val myFirstList : ‘a list
val stringList : string list = [“some string entry”]
val newStringList : string list =
[“another string entry”; “some string entry”]
“myFirstList” was a list of no set type yet. Then “stringList” became a list of strings due to the type of the first entry. Then we added a new element to the head of the list and created a new list “newStringList”. Compared to C# and Java this is a really cumbersome way of adding elements to a list but F# takes immutability very seriously.
What if we try to add an integer to newStringList?
let test = 10 :: newStringList
The compiler will show an error: The type ‘int’ does not match the type ‘string’ .
The ‘@’ operator concatenates two lists which is an approximation of the AddRange function of List of T in C#:
let stringListOne = ["frogs";"ambitious";"organic"] let stringListTwo = ["play";"halting";"obscene"] let joinedList = stringListOne @ stringListTwo
“joinedList” will contain the following elements:
[“frogs”; “ambitious”; “organic”; “play”; “halting”; “obscene”]
The above code example also shows how to declare a list with some starting elements. Note how the elements are delimited by a semi-colon.
In case you’re wondering where those random words are coming from then check out this random word generator.
View all F# related articles here.