Dakaa
Dakaa

Reputation: 199

F# how to for loop from -1 to 1 or 1 to -1?

I want something like j = 1 .. j = -1 and i = -1 .. i = 1, I know the Java/C# way of doing it, but not in F#.

   for j in 1 .. -1 do
    for i in -1 .. 1 do
      //all 9 combination.

Guidance please, thankyou.

Upvotes: 3

Views: 149

Answers (4)

Søren Debois
Søren Debois

Reputation: 5688

If you are really just counting -1, 0, 1, then it might be clearer to just write it out:

for j in [1; 0; -1] do
  for i in [-1; 0; 1] do
    printfn "%d,%d" i j

Upvotes: 1

Mark Seemann
Mark Seemann

Reputation: 233277

Both Jaya's and Phillip Trelford's answers are good. If you want a sequence of all the combinations instead of an imperative loop, you can do this:

let combinations =
    [1 .. -1 .. -1]
    |> Seq.collect (fun i -> [-1 .. 1] |> Seq.map (fun j -> (i, j)))

This produces a sequence like this (when converted to a list):

[(1, -1); (1, 0); (1, 1); (0, -1); (0, 0); (0, 1); (-1, -1); (-1, 0); (-1, 1)]

If you want a different order, you can always sort the tuples, but it might be more efficient to generate the sequence differently. If, for example, you want this sequence:

(-1,1) (0,1) (1,1) (-1,0) (0,0) (1,0) (-1,-1) (0,-1) (1,-1)

you can simply switch i and j around:

let combinations =
    [1 .. -1 .. -1]
    |> Seq.collect (fun i -> [-1 .. 1] |> Seq.map (fun j -> (j, i)))

which produces this sequence (converted to a list for readability):

[(-1, 1); (0, 1); (1, 1); (-1, 0); (0, 0); (1, 0); (-1, -1); (0, -1); (1, -1)]

Upvotes: 2

Phillip Trelford
Phillip Trelford

Reputation: 6543

When looping down to a number you can use the downto keyword:

for j = 1 downto -1 do
  for i = -1 to 1 do

or you can use the for in range syntax in @Jaya's answer.

Upvotes: 8

Jay
Jay

Reputation: 1309

   for j in 1.. -1 .. -1 do
     for i in -1 .. 1 .. 1 do
        printf "%d , %d" i j

Upvotes: 5

Related Questions