Exercise 5: Pattern Matching and Recursion
Pattern matching in F# is similar to switch statements in C#; however they provide abilities and functionality beyond the C# construct, particularly when used in concert with F#’s implementation of lists and recursion. In this Exercise you will be introduced to F#’s pattern matching syntax and see some examples which highlight the power of pattern matching.
Task 1 – Using Simple Pattern Matching to Output Information
In this task you will learn the basic pattern matching syntax in F#.
Task 2 – Using Simple Pattern Matching and Recursion to Implement the Fibonacci Sequence
In this task you will learn to supplement pattern matching in F# with recursive functions. Recursion is defining a function in terms of itself. In the following example if x is not 0 or 1, the function calls itself passing values derived from x. This approach is often used in functional programming in place of loops as it can make algorithms easier to understand.
Task 3 – Using Recursion with F# Lists
F#’s recursion ability also makes it ideal for processing items in a list. This task will simulate performing some sort of processing on items in a list in a recursive manner.