F# : iterate through int array

Viewed 560

I wanted to iterate through an array and every element has three integers. Is it possible to iterate through every integer within this array? The code below doesn't work because it gives the following error:

"The type 'int * int * int' is not compatible with the type 'seq<'a>'"

module Practice2

    let dataSet = 
        [|10, 20, 10; -20, -30, 10; 30, 50, 0;|]
        |> Seq.mapi (fun i elem -> 
            elem
            |> Seq.map (fun a -> printf("TEST"))
            );

I am completely new to F# so please correct me if this is completely the wrong approach.

2 Answers

Welcome to F#. Your data is an array of 3-tuples. F# says as much, when you evaluate this expression:

[|10, 20, 10; -20, -30, 10; 30, 50, 0|]
// val it : (int * int * int) [] = [|(10, 20, 10); (-20, -30, 10); (30, 50, 0)|]

Of course you can iterate this array with an index. Generally, use functions from that module that relates to data structure you employ, here Array.

[|10, 20, 10; -20, -30, 10; 30, 50, 0|]
|> Array.iteri (printfn "%i: %A")
// 0: (10, 20, 10)
// 1: (-20, -30, 10)
// 2: (30, 50, 0)

Now, for a real array of arrays, you may easily define your own functions. We're going to build a function that iterates this array of arrays. Therefore, two indices i and j, for the outer and inner array.

module Array =
    let iteri2 f = Array.iteri (fun i -> Array.iteri (f i))
    // val iteri2 : f:(int -> int -> 'a -> unit) -> ('a [] [] -> unit)
[|[|10; 20; 10|];[|-20; -30; 10|];[|30; 50; 0|]|]
|> Array.iteri2 (printfn "%i, %i: %i")
// 0, 0: 10
// 0, 1: 20
// 0, 2: 10
// 1, 0: -20
// 1, 1: -30
// 1, 2: 10
// 2, 0: 30
// 2, 1: 50
// 2, 2: 0

A suggestion:

let dataSet = 
    [10, 20, 10; -20, -30, 10; 30, 50, 0]
    |> List.collect (fun (a,b,c) -> [a;b;c])    //transforms (int*int*int) list into an int list
    |> List.iter (fun _ -> printfn "TEST")      //prints
Related