Piping, Composition, and Currying

后端 未结 2 405
無奈伤痛
無奈伤痛 2021-02-02 13:21

It seems to me that all of these are related. What is the difference?

2条回答
  •  深忆病人
    2021-02-02 14:00

    In addition to what Daniel wrote, there is a very close correspondence between piping (the |> and <| operators) and function composition (the >> and << operators).

    When you use piping to pass some data to a seqence of functions:

    nums |> Seq.filter isOdd
         |> Seq.map square
         |> Seq.sum
    

    ... then this is equivalent to passing the input to a function obtained using function composition:

    let composed = 
         Seq.filter isOdd
      >> Seq.map square
      >> Seq.sum
    
    composed nums
    

    In practice, this often means that you can replace function declaration that uses piping on the argument with a composition of functions (and use the fact that functions can be used as values). Here is an example:

    // Explicit function declaration
    foo (fun x -> x |> bar |> goo)
    
    // Equivalent using function composition
    foo (bar >> goo)
    

提交回复
热议问题