I just want to talk about one example from the F# Core library. Here is an example from the Seq module:
let length (ie : seq<'a>) =The
use e = ie.GetEnumerator()
let mutable state = 0
while e.MoveNext() do
state <- state + 1;
lengthfunction takes any sequence and returns an int. The first line of the function retrieves the enumerator for the sequence. The second line declares a mutable identifier clearly labeled
state. The rest of the function simply moves through the enumerator incrementing the count. Finally, the function returns the final count. Do the internals of the
lengthfunction surprise you? This example is very similar to how a length might be determined in an imperative context and it highlights my favorite feature of F#: it's your choice. You certainly can implement
lengthwith a recursive function and an accumulating value but would it be as fast as the version shown above? Would it be as easy to understand? You decide.
Choices abound when using F# and one of the most important choices you can make will be whether or not to use state. The point of these last two posts are to highlight this quality of F#. State is generally discouraged but it is always available should you choose to use it.