Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - how to write nested loops in a recursive way?

Given the following C# code:

var product = new List<int>();
for (int n1 = 100; n1 < 1000; n1++)
{
    for (int n2 = 100; n2 < 1000; n2++)
    {
        product.Add(n1 * n2);
    }
 }

What would be the equivalent F# code written in a functional style?

like image 433
michael_erasmus Avatar asked Nov 28 '22 12:11

michael_erasmus


1 Answers

I would just write it that way with the for-loops. Even a Haskell programmer would probably express this with a list comprehension, in which case you could write e.g.

let productsList =
    [for x in 2..4 do
     for y in 2..4 do
     yield x*y]

in F#.

like image 65
Brian Avatar answered Dec 15 '22 02:12

Brian