【问题标题】:Create tuples from seq of arrays.从数组的 seq 创建元组。
【发布时间】:2011-01-12 22:25:17
【问题描述】:

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

所以我想拿这个

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

把它变成

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

提前致谢。

【问题讨论】:

  • 正如@gradbot 指出的那样,您的示例输出与 Seq.Windowed 不对应(“windows”而不是“paging”)

标签: f# tuples


【解决方案1】:
> 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)]

【讨论】:

    【解决方案2】:

    我不确定它是否是 typeo,但您的数据与 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)
    

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

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 2017-01-30
      • 2018-09-19
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多