All the code of the samples can be down loaded here.
In functional programming, as with imperative programming, collections are very import. F# has support of two types of collections natively the list and the array. The list is a purely functional data structure because it is immutable. The array is not and is mutable, it was included in caml because of it’s performance and interoperability benefits.
F# has syntax which allows the definition of list as literals in a program, below is shown an example of an empty list and a list of integers.
let emptyList = []
let integerList = [1; 2; 3; 4; 5; 6; 7; 8]
Lists are similar to are forward only data structures, it’s very common to use recursion to deal with them using recursion. Generally you have a recursive case that deals with the head of the list and a base case that deals with the empty list. A function to double a list of integers, that follows that pattern, is shown below.
let rec doubleList list =
match list with
| head :: tail -> head * 2 :: doubleList tail
| [] -> []
At the moment F# supports two kinds of Arrays, caml style polymorphic arrays and C# arrays. The differences are a little subtle to explain here but all you really need to know is if you want interoperate with C# use “Arr” type of arrays and if you want your code to be compatible with caml use the “Array” style arrays. When the next version of the framework is released C# will support polymorphic arrays and the “Arr” type will probably become obsolete. For now this tutorial will only look at the “Array” type of array, because their behaviour is very similar.
Again F# has syntax which allows the definition of arrays as literals in a program, below is shown the definition of an empty array and an array of integers.
let emptyArray = [||]
let integerArray = [|1; 2; 3; 5; 6; 7; 8|]
The most common way to deal with the items in an array is the use of the “for to done” construct. This construct has several differences from an imperative for loop that help in fit into a functional programming language. The most important difference is that it has a return value, after the done statement you must say what value will be returned from for loop. To illustrate this, a function that takes an array of integers and doubles it is shown below.
let doubleArray arr =
let len = Array.length arr in
for index = 0 to len - 1 do
Array.set arr index ((Array.get arr index) * 2)
done;
arr
As you can see the arr identifier is return for loop and therefore is the function’s return value. The other thing to note about the for loop construct is whatever operation is part of the loop it must have a return value of unit, that is the equivalent of a method returning void in C#.