Here we will continue and build on the foundation from the previous chapter on functional programming basics. We will examine some of the more advanced and at the same time useful constructs of the F# language.
Recursion is a fundamental building block in functional programming. Many problems can be solved in a recursive fashion, and together with pattern matching, it makes up a powerful toolkit.
To define a recursive expression, you use the keyword rec
.
Let's start by looking at the famous Fibonacci sequence, which is defined as the sum of the two previous numbers in a recursive sequence. The first two values are set to 0
and 1
, respectively, as seed values:
let rec fib n = if n <= 2 then 1 else fib (n - 1) + fib (n – 2)
Recursion is a powerful way of solving problems, and is often preferred in functional languages before loop constructs. Let's look at three recursive functions to illustrate its flexibility and power:
let rec sum list...