F# — Pipe Forward and Pipe Backward

I’m tak­ing a bit of time to brush up my knowl­edge of F# and see if I can write bet­ter F# code and one of the things I notice is that whilst I use pipe-for­ward oper­a­tor (|>) often when work­ing with col­lec­tions I don’t near­ly use the pipe-back­ward oper­a­tor (<|) as fre­quent­ly as I should. It makes sense as the pipe-for­ward oper­a­tor works sim­i­lar to the way LINQ and IEnu­mer­able works, just to remind myself and oth­ers like me how these work:

Pipe-forward operator (|>)

Pipe-for­ward oper­a­tor lets you pass an inter­me­di­ate result onto the next func­tion, it’s defined as:

let (|>) x f = f x

For instance, to apply a fil­ter (i.e. IEnumerable.Where) for even num­bers to a list of inte­gers from 1 to 10, you can write:

image

You can add fur­ther pro­cess­ing steps to this inter­me­di­ate result:

image

For­ward com­po­si­tion oper­a­tor (»)

The for­ward com­po­si­tion oper­a­tor lets you ‘com­pose’ func­tions togeth­er in a way sim­i­lar to the way the pipe-for­ward oper­a­tor lets you chain func­tion del­e­gates togeth­er, it is defined as:

let (») f g x = g (f x)

Now imag­ine if you have two func­tions:

image

You can use them to build a high-order func­tion that returns triples the square of a float, n, using the » oper­a­tor:

image

This is syn­tac­ti­cal­ly clean­er and eas­i­er to read than:

image

and it’s espe­cial­ly use­ful when chain­ing togeth­er a large num­ber of func­tions.

Pipe-backward operator (<|)

The pipe-back­ward oper­a­tor takes a func­tion on the left and applies it to a val­ue on the right:

let (<|) f x = f x

As unnec­es­sary as it seems, the pipe-back­ward oper­a­tor has an impor­tant pur­pose in allow­ing you to change oper­a­tor prece­dence with­out those dread­ed paren­the­ses every­where and improve read­abil­i­ty of your code,.

For exam­ple:

image

can be writ­ten as

image

Back­ward com­po­si­tion oper­a­tor («)


The inverse of the for­ward com­po­si­tion oper­a­tor, the « oper­a­tor takes two func­tions and applies the right func­tion first and then the left, it’s defined as:

let («) f g x = f (g x)

Most­ly I find it more suit­able than the for­ward com­po­si­tion oper­a­tor in cas­es where you want to negate the result of some func­tion, for exam­ple, to find the odd num­bers in a list:

image