For-each loops in F#

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to For-each loops in F#

  1. Pingback: For-each loops in F# - Tech Geek Eden

  2. Pingback: For-each loops in F# - Path to Geek

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: