For in F#

F# provides several ways to create loops. Let’s explore different types of loops and their usage.

open System

// The most basic type, with a single condition
let mutable i = 1
while i <= 3 do
    printfn "%d" i
    i <- i + 1

// A classic initial/condition/after loop
for j = 0 to 2 do
    printfn "%d" j

// Another way of accomplishing the basic "do this N times" iteration
for i in 0..2 do
    printfn "range %d" i

// Infinite loop until break
let mutable shouldContinue = true
while shouldContinue do
    printfn "loop"
    shouldContinue <- false

// You can also continue to the next iteration of the loop
for n in 0..5 do
    if n % 2 = 0 then
        continue
    printfn "%d" n

When you run this program, you’ll see the following output:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Let’s break down the different types of loops used in this F# code:

  1. The while loop is used for the most basic type of loop with a single condition. It continues executing while the condition is true.

  2. The for loop with the to keyword is used for a classic initial/condition/after loop. It iterates from the start value to the end value (inclusive).

  3. The for loop with the in keyword and range operator .. is used to iterate over a sequence of numbers.

  4. An infinite loop is created using a while true loop, and we use a mutable variable to control when to break out of the loop.

  5. The continue keyword is used to skip to the next iteration of the loop when a certain condition is met.

F# provides these looping constructs to handle various scenarios in your programs. The choice of which loop to use depends on the specific requirements of your task.