F# – for in loop

  • Post author:
  • Post category:F#
  • Post comments:2 Comments
F# - for in loop

F# for in loop this looping construct is used to iterate over the matches of a pattern in an enumerable collection such as a range expression, sequence, list, array, or other constructs that supports enumeration.

Syntax of F# for in loop

for pattern in enumerable-expression do
   body-expression

Example

The following program illustrates the concept −

// Looping over a list.
let list1 = [ 10; 25; 34; 45; 78 ]
for i in list1 do
   printfn "%d" i

// Looping over a sequence.
let seq1 = seq { for i in 1 .. 10 -> (i, i*i) }
for (a, asqr) in seq1 do
   printfn "%d squared is %d" a asqr

When you compile and execute the program, it yields the following output −

10
25
34
45
78
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

Next Topic – Click Here

This Post Has 2 Comments

Leave a Reply