For-each loops in F#
March 5, 2017 2 Comments
For-each loops in F# are declared using the keywords for, in and do.
Here’s how to iterate through a list of integers:
let myList = [1..10] let loopTester = for i in myList do printfn "Current value: %i" i
Executing the function loopTester gives the following output:
Current value: 1
Current value: 2
Current value: 3
Current value: 4
Current value: 5
Current value: 6
Current value: 7
Current value: 8
Current value: 9
Current value: 10
For-each loops are often used in conjunction with list comprehensions to build new lists or ranges. Another keyword to learn here is ‘yield’ which is similar to the yield keyword in C#:
let myList = [1..10] let myModifiedList = [for i in myList do yield i + 2]
myModifiedList will contain the same elements as myList except that we add 2 to each:
int list = [3; 4; 5; 6; 7; 8; 9; 10; 11; 12]
The “do yield” construct can be shortened with ‘->’ as follows:
let myList = [1..10] let myModifiedList = [for i in myList -> i + 2]
myModifiedList is will be the same as before.
View all F# related articles here.
Pingback: For-each loops in F# - Tech Geek Eden
Pingback: For-each loops in F# - Path to Geek