代码之家  ›  专栏  ›  技术社区  ›  Matěj Pokorný

更好的行求和方法

  •  3
  • Matěj Pokorný  · 技术社区  · 8 年前

    我正在学习F#(又一次),并尝试在excel中对一些行求和。这是我的尝试。

    let sumRows (source: seq<double[]>) =
        source
        |> Seq.reduce (fun a b -> (a, b) ||> Seq.map2 (fun x y -> x + y) |> Seq.toArray)
    

    能做得更好吗?我已经发现了双前向管道操作员,但现在,整个部分 fun a b -> (a, b) ||>

    1 回复  |  直到 8 年前
        1
  •  4
  •   AMieres    8 年前

    是的,它是多余的,因为只有当您需要将元组转换为两个单独的参数时,double-pipe操作符才很方便。在本例中,您已经将它们作为两个单独的参数,因此您可以这样传递它们:

    let sumRows (source: seq<double[]>) =
        source
        |> Seq.reduce (fun a b -> Seq.map2 (fun x y -> x + y) a b |> Seq.toArray)
    

    我们可以摆脱 |> Seq.toArray Seq.map2 具有 Array.map2

    let sumRows (source: seq<double[]>) =
        source
        |> Seq.reduce (fun a b -> Array.map2 (fun x y -> x + y) a b)
    

    现在我们可以通过删除 fun a b ->

    let sumRows (source: seq<double[]>) =
        source
        |> Seq.reduce (Array.map2 (fun x y -> x + y) )
    

    最后,你知道像这样的接线员 + 插入括号 (+) ?

    let sumRows2 (source: seq<double[]>) =
        source
        |> Seq.reduce (Array.map2 (+) )
    

    所有这些版本都有相同的签名,它们都是正确的。你选哪个更适合你的风格。

    顺便说一句,你可能想更进一步,这样做:

    let sumRows2 = Seq.reduce (Array.map2 (+) )
    

    Value restriction

    推荐文章