Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Language Basics

F# if/else Expressions and for, while and Loops

Learn F# control flow: if/elif/else as expressions, for-to and for-in loops, while loops, early exit patterns, and why recursion and collection functions replace most loops.

Control flow in F# looks familiar, but with one big twist: if is an expression that returns a value. That removes the need for a ternary operator and for many temporary variables. This lesson covers if, the loops (for ... to, for ... in, while), the fact that F# has no break or continue, and what to do instead.

if is an expression

FSHARP
let sign n =
    if n > 0 then "positive"
    elif n < 0 then "negative"
    else "zero"

let message = if sign 5 = "positive" then "good" else "check"

Every branch must return the same type, and an if used as a value needs an else. Without an else the branch must return unit, which makes it a statement for side effects:

FSHARP
let checkStock count =
    if count = 0 then
        printfn "Out of stock!"
    printfn "Checked."

This does not work as a value-returning if: let x = if true then 5 is a compile error, because the missing else would have type unit, not int.

You can combine conditions with &&, || and not. There is no truthiness: the condition must be a bool. if count then ... with an int does not compile.

for ... to

A counting loop. Both ends are inclusive:

FSHARP
for i in 1 .. 5 do
    printf "%d " i
printfn ""
// 1 2 3 4 5

The older, still valid form is for i = 1 to 5 do. Count downward with downto or a negative step:

FSHARP
for i = 5 downto 1 do printf "%d " i       // 5 4 3 2 1
for i in 10 .. -3 .. 0 do printf "%d " i   // 10 7 4 1

The range start .. step .. stop works anywhere. It also works with floats and characters: ['a' .. 'e'].

for ... in

Loop directly over any collection (list, array, sequence, string, map...):

FSHARP
let fruits = [ "apple"; "banana"; "cherry" ]
for fruit in fruits do
    printfn "I like %s" fruit

for (i, fruit) in List.indexed fruits do
    printfn "%d: %s" i fruit

Notice the second loop: a pattern (i, fruit) takes the tuple apart. List.indexed pairs each item with its position, so you almost never need a manual index counter.

while

FSHARP
let mutable n = 27
let mutable steps = 0
while n <> 1 do
    n <- if n % 2 = 0 then n / 2 else 3 * n + 1
    steps <- steps + 1
printfn "%d steps" steps       // 111 steps

while needs state that changes, so it is the one place where mutable is common. If you catch yourself writing a while that builds a result, consider recursion (Recursion) or Seq.unfold.

No break and no continue

F# deliberately has no break or continue. Alternatives:

  1. Filter first instead of continue:

    FSHARP
    for n in [ 1 .. 10 ] |> List.filter (fun n -> n % 2 = 1) do
        printf "%d " n
    
  2. Search with a function instead of break: List.tryFind, Seq.exists, Seq.takeWhile, List.forall.

    FSHARP
    let firstBig = [ 3; 8; 15; 4 ] |> List.tryFind (fun n -> n > 10)   // Some 15
    
  3. Use a mutable flag in a while loop condition, when state is unavoidable.

  4. Recursion, which stops by simply not calling itself again.

Most "for loop with an accumulator" patterns collapse into one pipeline. Summing squares of the evens is [1..10] |> List.filter (fun n -> n % 2 = 0) |> List.sumBy (fun n -> n * n). Pipelines are shown in Pipelines and composition.

Loops return unit

The body of a loop must be unit. Results are communicated by side effects (printing, mutation) or, better, by building collections with [ for ... ] comprehensions:

FSHARP
let squares = [ for i in 1 .. 5 -> i * i ]            // [1; 4; 9; 16; 25]
let evens = [ for i in 1 .. 10 do if i % 2 = 0 then yield i ]

You will use these a lot in Collections.

Nested loops and a multiplication table

FSHARP
for row in 1 .. 3 do
    for col in 1 .. 3 do
        printf "%3d" (row * col)
    printfn ""

Prints:

TEXT
  1  2  3
  2  4  6
  3  6  9

Run it: C# stand-ins

C# has the same constructs plus break and continue. These stand-ins compute what the F# loops above do.

C# C# stand-in: the sign function and a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: Collatz steps with while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is special about if in F#?

    if/else returns a value, so you can bind it with let or return it from a function.
  2. 2. Why does let x = if true then 5 fail to compile?

    An if without else must be unit. A value-returning if needs both branches.
  3. 3. What does for i in 1 .. 3 do iterate over?

    F# ranges are inclusive on both ends.
  4. 4. What replaces break in F#?

    F# has no break or continue; search and filter functions or recursion do the job.

Summary

  • if/elif/else returns a value; branches must have the same type; the condition must be bool.
  • for i in a .. b is inclusive; use downto or a negative step to count down.
  • for x in collection iterates directly, and List.indexed supplies indexes.
  • while needs mutable state; there is no break or continue.
  • Comprehensions and collection functions replace most loops.

Next: Tuples and unit