Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# syntax for repeated pipelining

Tags:

f#

Is there any syntax in F# which allows pipelining by a list of functions in sequence concisely? For example,

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

Or is there a design pattern which makes this task unnecessary? In my case I am making a (naive) Sudoku solver and have a function that looks like this:

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)

Is there any way to clean up something like this?

like image 600
Paul Orland Avatar asked Nov 16 '12 17:11

Paul Orland


2 Answers

One way to look at this is folding on pipelining operator |> instead of folding on data:

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

In general, if fun1, fun2, etc have the same signature, you can apply |> on a sequence of functions i.e. repeated pipelining:

  [
   fun1; 
   fun2; 
   fun3;
   //...
         ] |> List.fold (|>) x
like image 178
pad Avatar answered Nov 03 '22 00:11

pad


Looks like a fold to me. What about

let reduceByRows poss = 
  Seq.fold (fun p i -> reduceBy (rowIndices i) p) poss {1..9}
like image 40
Daniel Avatar answered Nov 03 '22 00:11

Daniel