tags:

views:

197

answers:

2

Basically I'm looking to take the output of Seq.Windowed which returns a sequence of arrays and turn it into a sequence of tuples

so I want to take this

[[|1;2;3|];[|4;5;6|]]

and turn it into

[(1,2,3);(4,5,6)]

Thanks in advance.

+4  A: 
> let x =  [[|1;2;3|];[|4;5;6|]];;

val x : int [] list = [[|1; 2; 3|]; [|4; 5; 6|]]

> let y = [for [|a; b; c|] in x do yield (a, b, c)];;

  let y = [for [|a; b; c|] in x do yield (a, b, c)];;
  ----------------------------^

stdin(6,29): warning FS0025: Incomplete pattern matches on this expression.
For example, the value '[|_; _; _; _|]' may indicate a case not covered by
the pattern(s).

val y : (int * int * int) list = [(1, 2, 3); (4, 5, 6)]

If you can guarantee that all of your arrays have the same shape, you can ignore the warning above. If the warning really bothers you, you can write:

> x |> List.map (function [|a;b;c|] -> a, b, c | _ -> failwith "Invalid array length");;
val it : (int * int * int) list = [(1, 2, 3); (4, 5, 6)]
Juliet
thanks. this works for what I'm doing right now
AvatarOfChronos
+3  A: 

I'm not sure if it is a typeo or not but your data doesn't match windowed.

let firstThreeToTuple (a : _[]) = (a.[0], a.[1], a.[2])

seq {1 .. 6}
|> Seq.windowed 3
|> Seq.map firstThreeToTuple
|> Seq.iter (printfn "%A")

(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)

If you want a function that takes a sequence and chops it up into a sequence of arrays you can use this code from another question.

let chunks n (sequence: seq<_>) =
    let fold_fce (i, s) value = 
        if i < n then (i+1, Seq.append s (Seq.singleton value))
                 else (  1, Seq.singleton value)
    in sequence
    |> Seq.scan (fold_fce) (0, Seq.empty)
    |> Seq.filter (fun (i,_) -> i = n)
    |> Seq.map (Seq.to_array << snd )

Then you can run the result through firstThreeToTuple.

seq {1 .. 6}
|> chunks 3
|> Seq.map firstThreeToTuple
|> Seq.iter (printfn "%A")

(1, 2, 3)
(4, 5, 6)
gradbot