F# Loops

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.

  1. for… to and for… downto expressions
  2. for … in expression
  3. While…do loop
  4. 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

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 

let main() = for i = 1 to 10 do printfn "Number: %i" i main()

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 

let main() = for i = 10 downto 1 do printfn "Number: %i" i main()
Number: 10
Number: 9
Number: 8
Number: 7
Number: 6
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1

Example Explanation

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.

Syntax

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:

Example: 

let list1 = [ 1; 78; 120; 12; 29; 45 ] for i in list1 do printfn "%d" i
Following is an output of the example above:
1
78
120
12
29
45

In the example below let’s take the sum of the above example list:

Example: 

let list1 = [ 1; 78; 120; 12; 29; 45 ] let mutable sum:int32 = 0 for i in list1 do sum <- sum + i printfn "%d" sum

The above example will output as follows:

1
79
199
211
240
285

Example Explanation

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.

Syntax

while test-expression do
     body-expression

Following is an example of iterating values from 1 to 10 using a while loop:

Example: 

let mutable a = 1 while (a <= 10) do printfn "Number a: %d" a a <- a + 1

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

Example Explanation

This is an F# code that uses a while loop to print numbers from 1 to 10.

  1. The variable a is defined as a mutable integer with an initial value of 1.
  2. 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.
  3. 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.
  4. After printing the value of a, we increment the value of a by 1 using the statement a <- a + 1.
  5. The loop iterates until a is no longer less than or equal to 10.
  6. 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:

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:

Example: 

let main() = for i = 1 to 5 do printfn " " for j=1 to 2*i-1 do printf "*" main()
The following example prints the output as follows:
*
***
*****
*******
*********

Example Explanation

This is an F# code that prints a pyramid of asterisks with 5 rows.

  1. The main function is defined without input arguments.
  2. 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.
  3. Before we print the asterisks for each row, we use printfn ” ” to print a newline character, which moves the cursor to the next line.
  4. 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.
  5. 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.
  6. Inside the inner loop, we use printf “*” to print an asterisk character.
  7. 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.
  8. Finally, we call the main function to run the code and print the pyramid.

The following example illustrates the use of nested while loops:

Example: 

let mutable a=1; while(a<=3) do let mutable b = 1; while (b < 3) do printfn "%d %d" a b b<- b+1 a<- a+1
The output of the example above is as follows:
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.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *