WHAT'S IN THIS CHAPTER?
Branching with if/else
Looping with while/do
Looping with for
Much, if not all, of the power of a programming language derives from its capability to branch based according to particular criteria and values in various ways, also known as control flow expressions. Like its sister languages on the .NET platform, F# has a wide range of powerful control flow constructs, including one whose power is such that it merits its own chapter, pattern-matching, discussed in Chapter 6.
The simplest control flow construct to understand and come to know, of course, is the simple branching construct based on a single Boolean decision criteria: the
let x = 12 if x = 12 then System.Console.WriteLine("Yes, x is 12")
then keyword is mandatory, indicating the end of the criteria test and the start of the body of the code to execute in the case when the test passes true. For this reason, parentheses are unnecessary around the criteria test.
Also, similar to how C# refuses to allow anything other than a Boolean expression to be used in the comparison clause of its
if statement, F# refuses to automatically convert non-
bool values into
bool values, so the following refuses to compile:
let x = 12 if x then System.Console.WriteLine("Yep, x")
The issue here isn't one of trying to prevent programmers from accidentally performing an assignment (as was the case in C/C++ years ago), but that the F# language refuses to ...