In F# a loop continues forward—we implement loops with for and while. Loops are powerful, but functional-based designs are usually emphasized in this language.
In this language, declarative constructs are often preferred. But for getting things done, loops are often a good choice—and they can be rewritten later if needed.
This program shows 2 for
-loops, and both of the constructs loop over the same values. In programs, either form can be used.
for
-loop uses an iteration variable called "i" and goes from 0 through 3 inclusive.// Loop from 0 through 3 inclusive. // ... The variable i is incremented by 1 each time. for i = 0 to 3 do printfn "For, to: %A" i // This is the same loop but with a range. for i in 0 .. 3 do printfn "For, in: %A" iFor, to: 0 For, to: 1 For, to: 2 For, to: 3 For, in: 0 For, in: 1 For, in: 2 For, in: 3
For
-in, listA for-in
loop enumerates over each element in a collection (like a list). Here we create a list of ints called "codes."
for-in
loop accesses all elements in the list. It provides no indexes, so the syntax is simpler.let codes = [3; 12; 34; 3] // Loop over ints from list. for code in codes do // If code is 3 then write a special word. if (code = 3) then printfn "Three" // Write value of int from list. printfn "%A" codeThree 3 12 34 Three 3
With this keyword we create a decrementing loop. After each iteration, the iteration variable (in this program "i") is reduced by 1.
// Specify a decrement for-loop with downto. for i = 10 downto 6 do printfn "%A" i10 9 8 7 6
The most versatile loop in F# is the while
-loop. Here we can increment, decrement, or loop forever. We must be careful not to make mistakes.
while
-loop should be marked as mutable so we can change it.// Use an iteration variable that starts at 4. // ... The variable must be mutable. let mutable x = 4 // Continue looping while x is positive. while x >= 0 do // Write value. printfn "%A" x // Decrement x. x <- x - 14 3 2 1 0
In functional programs, recursion and method-based iteration is often preferred. But loops are still wonderful. In F# we can use iteration and increment variables.