用于重复流水线操作的F#语法

时间:2012-11-16 17:18:49

标签: f#

F#中是否有任何语法允许按顺序通过一系列函数进行流水线操作?例如,

    x |> fun1 |> fun2 |> fun3 ...

或者是否有设计模式使这项任务变得不必要?在我的情况下,我正在制作一个(天真的)数独求解器并且具有如下所示的函数:

let reduceByRows poss = 
    poss 
    |> reduceBy (rowIndeces 1) |> reduceBy (rowIndeces 2) |> reduceBy (rowIndeces 3)
    |> reduceBy (rowIndeces 4) |> reduceBy (rowIndeces 5) |> reduceBy (rowIndeces 6)
    |> reduceBy (rowIndeces 7) |> reduceBy (rowIndeces 8) |> reduceBy (rowIndeces 9)

有没有办法清理这样的东西?

2 个答案:

答案 0 :(得分:8)

一种看待这种情况的方法是在流水线操作符|>上折叠而不是折叠数据:

{1..9} |> Seq.map (rowIndices >> reduceBy)
       |> Seq.fold (|>) poss

通常,如果fun1fun2等具有相同的签名,您可以对一系列函数应用|>,即重复流水线:< / p>

  [
   fun1; 
   fun2; 
   fun3;
   //...
         ] |> List.fold (|>) x

答案 1 :(得分:7)

看起来像是我的折叠。

怎么样?
let reduceByRows poss = 
  Seq.fold (fun p i -> reduceBy (rowIndices i) p) poss {1..9}
相关问题