从seq数组创建元组。

时间:2010-02-04 04:54:55

标签: f# tuples

基本上我想要获取Seq.Windowed的输出,它返回一个数组序列并将其转换为元组序列

所以我想拿这个

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

并将其转换为

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

提前致谢。

2 个答案:

答案 0 :(得分:5)

> 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)]

如果您可以保证所有阵列具有相同的形状,则可以忽略上面的警告。如果警告真的困扰你,你可以写:

> 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)]

答案 1 :(得分:5)

我不确定它是否是一个类型,但你的数据与窗口不匹配。

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)

如果你想要一个接受序列并将其切割成数组序列的函数,你可以使用另一个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 )

然后你可以通过firstThreeToTuple运行结果。

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

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