C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
First: The first for-loop uses an iteration variable called i and goes from 0 through 3 inclusive.
Second: This loop uses range syntax. The two periods are part of an inclusive range of 0, 1, 2 and 3.
F# program that uses for loops
// 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" i
Output
For, to: 0
For, to: 1
For, to: 2
For, to: 3
For, in: 0
For, in: 1
For, in: 2
For, in: 3
Note: The for-in loop accesses all elements in the list. It provides no indexes, so the syntax is simpler.
F# program that uses for-in loop over list
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" code
Output
Three
3
12
34
Three
3
F# program that uses for, downto
// Specify a decrement for-loop with downto.
for i = 10 downto 6 do
printfn "%A" i
Output
10
9
8
7
6
Mutable: The iteration variable used as a counter in a while-loop should be marked as mutable so we can change it.
Decrement: We decrement the variable x by assigning it the current value minus 1.
F# program that uses while-loop
// 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 - 1
Output
4
3
2
1
0
Quote: For-loops over ranges that are specified by variables are a primitive elaborated form. When executed, the iterated range includes both the starting and ending values in the range, with an increment of 1.
F# Language Specification: fsharp.org