Lesson 20. Program flow in F#
In C# and VB .NET, we have a variety of ways of performing what I consider program flow: branching mechanisms and, to an extent, loops. In this lesson, we’ll compare and contrast those features with equivalents in F#, looking at the following:
- for and while loops
- If/then statements and expressions
- Switch/case statements
- Pattern matching
When you’re finished, you’ll have a good idea of how to perform all sorts of complex conditional logic much more succinctly than you might be used to.
I cover loops briefly in this lesson because the F# side of things has a slightly different syntax compared to C# and VB .NET, with similar behavior. This leaves us more room to focus on branching logic in F#, which is much more interesting. You’ve already seen examples of these constructs in this book, so you can consider this reference material more than anything.
The main thing to know is that—comprehensions aside—these looping constructs, although officially expressions, are inherently imperative, designed to work with side effects (code that doesn’t have any tangible output; for example, printing to the console or saving to the database). In that respect, these loops should be familiar to you (and perhaps unsurprisingly not used as often in F# as C# or VB .NET).