Understanding F # Composition Operators

I am well versed in using operators >> and << in F #. However, looking at the source of F # to establish a deeper understanding, I was confused with this:

 let inline (>>) fgx = g(fx) let inline (<<) fgx = f(gx) 

How to interpret these expressions conceptually? Also, how would you describe these expressions? Do they determine the type?

+4
source share
2 answers

As the msdn page for F # functions shows , it says: "Functions in F # can be composed of other functions. The composition of two functions, function1 and function2, is another function that represents the application of function1, following the application of function2."

It can be considered similar to pipe operators, simply without specifying the last / deepest parameter; for example, the following two lines are equivalent:

 let composed = f >> g let piped x = g <| fx 

Also see this question for more information.

+2
source

I think the best way to describe this is an example, as looking at a definition can be a bit confusing. Say you had this:

 let isEven x = x % 2 = 0 [1 .. 99] |> List.filter (fun x -> not (isEven x)) 

Using composition operators, you can rewrite them as one of them:

 [1 .. 99] |> List.filter (isEven >> not) [1 .. 99] |> List.filter (not << isEven) 

More general, if you have something like this:

 data |> a |> b |> c 

You can rewrite it as follows:

 data |> (a >> b >> c) 

and interpret a >> b >> c in the same way as a, then do b and then c. If you prefer a more traditional reverse order:

 (a (b (c data))) 

you can rewrite it as

 ((a << b << c) data) 

This is also called a dotless style. In normal cases, it may be harder to read than using the regular style, but when moving to higher-order functions, it is easier to read, since you don't need to add noise (fun x -> ) .

+5
source

Source: https://habr.com/ru/post/1494596/


All Articles