O'Reilly logo

Professional F# 2.0 by Richard Minerich, Talbott Crowell, Aaron C. Erickson, Ted Neward

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Control Flow

WHAT'S IN THIS CHAPTER?

  • Branching with if/else

  • Looping with while/do

  • Looping with for

  • Handling exceptions

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.

BASIC DECISIONS: IF

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 if construct:

let x = 12
if x = 12 then
    System.Console.WriteLine("Yes, x is 12")

The 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required