Why use a backward pipe operator instead of a function chaining?
let distanceFromOrigin aPoint =
let square x = x * x
sqrt (square aPoint.x + square aPoint.y)
vs
let distanceFromOrigin aPoint =
let square x = x * x
sqrt <| square aPoint.x + square aPoint.y
As Scott Wlaschin pointed out here, the backward pipe operator is useful if you need to pass in data as the first parameter (rather than the last) somewhere along a chain of pipes. Consider the following:
amendedString
is "birthday Crappy". Let's say I want it to be "Crappy birthday" instead. I can achieve that by using the backward pipe operator:Now
amendedString
is "Crappy birthday", which is what I want.Because of the left associativity (
f <| g <| x
is parsed as(f <| g) <| x
and sadly not asf <| (g <| x)
which is equivalent tox |> g |> f
), I found it useful only when you want to remove parentheses (instead off (long expression)
, you writef <| long expression
).Choosing between
f x
,x |> f
andf <| x
is mainly a question of style. There's no absolute rule for choosing one instead of the other. The|>
operator is very popular, and it's a good idea to use it.<|
is less frequent, but if you look in the compiler's sources, you'll find a couple of uses. For example:<|
is used to remove a parenthesis, and I think it make the code more readable when used carefully. When you see it, you know the following expression is the argument to your function. You don't have to search for the closing parenthesis. I suggest you use it sparingly, and you should generally avoid mixing<|
and|>
in the same expression, as it can be very confusing.I sometimes enjoy using this operator to create a "block", with a
fun
orlazy
keyword.The block is based on indentation, so it fits quite well in F# code. Thanks to the
<|
operator, you don't need a trailing parenthesis.