For loops are used to execute the code repeatedly for a condition meet.
It is used to iterate an array or list types.
F# provides two types of for loops.
- for loop iterate ranges: Simple for loop with for to/downto to iterate the values with given start and increment/decrement until max value.
- for in loop to iterate range of values in Enumerable types such as array, set, collection types
F# For loops examples
for loop contains for to and downto versions
for to iterate with the initial value, increments until the end value is met. for downto iterates with an initial value, decrements until the end value is met. syntax
for variable=initial_expression to end_expression do
//body
for variable=initial_expression downto end_expression do
//body
Here is a for to loop example
for i = 1 to 3 do
printfn "%d" i;
Output:
1
2
3
Here is a for downto loop example
for i = 3 downto 1 do
printfn "%d" i;
Output:
3
2
1
- For in-loop to iterate enumerable types
for in-loop to iterate types such as collections
Syntax
for pattern in enumerable_list
// body
Here is an example [1..3] is a range of values from 1 to 3.
for i in [1..3] do
printfn "%d" i;
Another example of iterating a List of numbers
let numbers = [ 1;7;9;10 ];;
for value in numbers do
printfn "%i" value;
Output:
1
7
9
10