In F# what does the >> operator mean?

后端 未结 5 1023
悲&欢浪女
悲&欢浪女 2020-12-08 09:20

I noticed in some code in this sample that contained the >> operator:

let printTree =
  tree >> Seq.iter (Seq.fold (+) \"\" >> printfn \"%s\")
         


        
5条回答
  •  长情又很酷
    2020-12-08 10:21

    It's the function composition operator.

    More info on Chris Smith's blogpost.

    Introducing the Function Composition operator (>>):

    let inline (>>) f g x = g(f x)

    Which reads as: given two functions, f and g, and a value, x, compute the result of f of x and pass that result to g. The interesting thing here is that you can curry the (>>) function and only pass in parameters f and g, the result is a function which takes a single parameter and produces the result g ( f ( x ) ).

    Here's a quick example of composing a function out of smaller ones:

    let negate x = x * -1 
    let square x = x * x 
    let print  x = printfn "The number is: %d" x
    let square_negate_then_print = square >> negate >> print 
    asserdo square_negate_then_print 2
    

    When executed prints ‘-4’.

提交回复
热议问题