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.

Advertisements

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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: