Here in this article, we will discuss F# loops, their syntax, common use cases, and look at how to use loops in F#.
During this session, we will also discuss loop best practices and the most common mistakes that we should avoid when using loops.
After reading this article, you should have a clear understanding of how F# loops can be used to improve the efficiency and maintainability of your code.
To handle the looping requirements of the application, F# provides the following types of loops.
- for… to and for… downto expressions
- for … in expression
- While…do loop
- nested loops
F# Loops for…to and for…downto
In a for…to loop, a sequence of values is iterated over in increasing order, starting from a certain value and ending at a given value, until the value is reached.
On the other hand, for…downto loops are used to iterate over a sequence of values in decreasing order, starting with one value and ending with another, starting from a specified value and iterating through it.
For…to loops are used in the F# programming language in the following syntax
for var = start-expr to end-expr do ... // loop body
For…downto loops are written in the F# programming language with the following syntax
for var = start-expr downto end-expr do ... // loop body
In the following program, you will see the numbers 1 – 10 printed out:
F# Loops Example: 1
Following output will be printed after execution is complete:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: 7 Number: 8 Number: 9 Number: 10
Here is an example program that counts in reverse and prints out the numbers 10 – 1 as a result
F# Loops Example: 2
Number: 10 Number: 9 Number: 8 Number: 7 Number: 6 Number: 5 Number: 4 Number: 3 Number: 2 Number: 1
This code is an example of a basic loop in the F# programming language.
The code defines a function called main, which is the program’s entry point.
Within main, there is a for loop that counts down from 10 to 1 using the downto keyword.
During each iteration of the loop, the loop variable i is printed to the console using the printfn function, which is a formatted printing function that accepts a string and one or more values to be interpolated into the string.
The string being printed in this case is “Number: %i“, which contains a placeholder for an integer value. The i variable is provided as an argument to the printfn function, and it replaces the placeholder in the string.
Therefore, when the program is run, it will output numbers from 10 to 1, each preceded by the string “Number: “.
F# Loop – for…in
For…in loops in F# iterate over a sequence of values one by one. As each element in the sequence is executed, the loop variable is assigned the value of each of the elements and then the loop is repeated for each element in the sequence.
A loop of this type is often used when a series of items needs to be processed, such as a list of files, or when a sum or average must be computed.
During the process of processing data in F#, the for…in loop is often used as a mechanism to transform and filter data as it is processed, in conjunction with other functional programming constructs, such as pipelines.
for pattern in enumerable-expression do body-expression
Below is a simple example of a for..in loop to iterate over a list of items:
1 78 120 12 29 45
In the example below let’s take the sum of the above example list:
The above example will output as follows:
1 79 199 211 240 285
This F# code defines a list of integers called list1 containing six values, and a mutable integer variable called sum that is initially set to 0.
The code then uses a for…in loop to iterate over list1 elements. During each iteration of the loop, the loop variable i takes the value of the current element in the list.
Within the loop, the code updates the value of sum by adding the current element i to it using the <-mutable assignment operator. The updated sum value is then printed to the console using the printfn function.
In effect, this loop iterates over each element in the list and calculates the running sum of the elements, printing each intermediate sum to the console.
After the loop has completed, the final value of sum will contain the total sum of all the elements in the list. And the final value of sum would be 285, which is the sum of all the elements in the list.
F# – while..do Loops
F# allows you to repeatedly execute a block of code while a condition is true using the while..do loop, which is a control flow construct that can be applied to any block of code. This loop continues as long as the condition is not false.
There are some situations where it is useful to use this loop if you have to repeat a particular action over and over, for example reading from a file, processing data, or even waiting for an input from the user. This is a simple, flexible, and powerful construct that can be applied to a wide range of scenarios depending on the situation.
while test-expression do body-expression
Following is an example of iterating values from 1 to 10 using a while loop:
The output of the following example is as follows:
Number a: 1 Number a: 2 Number a: 3 Number a: 4 Number a: 5 Number a: 6 Number a: 7 Number a: 8 Number a: 9 Number a: 10
This is an F# code that uses a while loop to print numbers from 1 to 10.
- The variable a is defined as a mutable integer with an initial value of 1.
- The while loop checks if a is less than or equal to 10. If a is less than or equal to 10, the loop continues.
- Inside the while loop, we use printfn “Number a: %d” a to print the value of a on the console. %d is a placeholder that gets replaced by the value of a.
- After printing the value of a, we increment the value of a by 1 using the statement a <- a + 1.
- The loop iterates until a is no longer less than or equal to 10.
- After the loop completes, the program terminates.
F# Nested Loops
In programming, iterating over collections of data is among the most common concepts you will encounter, and F# enables you to do this in a variety of ways.
The nested loop is one of them. A nested loop refers to a loop within a loop. This method allows programmers to iterate over multiple data collections at the same time in a similar manner. In which each collection’s individual elements are iterated by the inner loop, while the outer loop controls the flow of the iterations.
A nested for loop could be expressed in the following way based on the following syntax:
for var1 = start-expr1 to end-expr1 do for var2 = start-expr2 to end-expr2 do ... // loop body
A nested while loop could be expressed in the following way based on the following syntax:
while test-expression1 do while test-expression2 do body-expression
The following example illustrates the use of nested for loops:
* *** ***** ******* *********
This is an F# code that prints a pyramid of asterisks with 5 rows.
- The main function is defined without input arguments.
- Inside the main function, we use a for loop to iterate from 1 to 5. The loop variable i represents the current row of the pyramid we are printing.
- Before we print the asterisks for each row, we use printfn ” ” to print a newline character, which moves the cursor to the next line.
- We use another for loop to print the asterisks for each row. The loop variable j represents the current column of the pyramid we are printing.
- The number of asterisks to be printed for each row is calculated using the formula 2*i-1. This formula gives us an odd number of asterisks for each row, which is necessary to create a symmetric pyramid.
- Inside the inner loop, we use printf “*” to print an asterisk character.
- After printing all the asterisks in a row, the printfn statement moves the cursor to the next line. This is ready for the next row to be printed.
- Finally, we call the main function to run the code and print the pyramid.
The following example illustrates the use of nested while loops:
1 1 1 2 2 1 2 2 3 1 3 2
Please subscribe to our newsletter below in order to stay up to date with all the latest developments in F# functional programming language and to learn more about the language.