Control structures
Control structures refer to the decisions made that affect the order of execution of the code. Although F# is an expression-based language, it also provides control flow constructs common of statement-based languages, such as looping, that allows us to write code with side-effects. We will be discussing this, as well as how to express conditions, in the following sections.
Looping
There are two types of loops: the for
loop and the while
loop. The For
loops have the following two types of expression:
for...to
: This iterates over a range of valuesfor...in
: This is more like theforeach
loop in other .NET languages as it loops over an enumerable collection
The for...to expression
The for...to
expression loops/iterates over a range of values. The range can be forward/reverse or generated via a function. The return of this expression is unit
type.
The forward expression works by incrementing the following values in the loop:
// A simple for...to loop.
let function1() =
for...