Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the F# Composition Operators

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

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

How do I interpret these expressions conceptually? Also, how would you describe these expressions? Are they defining a type?

like image 223
airietis Avatar asked Mar 22 '23 23:03

airietis


2 Answers

I think the best way to describe it is with an example, as looking at the definition can be a little confusing. Let's say you had this:

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

Using the composition operators you could rewrite it as one of these instead:

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

More genericly, if you have something like this:

data |> a |> b |> c

You can rewrite it like this:

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

and interpret a >> b >> c as do a, then do b, then do c. If you prefer the more traditional backwards ordering:

(a (b (c data)))

you can rewrite it as

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

This is also called the point free style. In normal cases it can be harder to read than using the normal style, but when passing to higher-order functions, it can be easier to read as you avoid having to add the (fun x -> ) noise.

like image 97
Gustavo Guerra Avatar answered Apr 01 '23 04:04

Gustavo Guerra


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

It can be thought of as similar to the pipe operators, just without specifying the last/deepest parameter; e.g. the following two lines are equivalent:

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

Also see this question for more information.

like image 33
Jwosty Avatar answered Apr 01 '23 05:04

Jwosty