Does it matter how I declare a pipeline? I know of three ways:
let hello name = "Hello " + name + "!"
let solution1 = hello <| "Homer"
let solution2 = "Homer" |> hello
Which would you choose? solution1 or solution2 - and why?
As mentioned the pipe-forward operator |>
helps with function composition and type inference. It allows you to rearrange the parameters of a function so that you can put the last parameter of a function first. This enables a chaining of functions that is very readable (similar to LINQ in C#). Your example doesn't show the power of this - it really shines when you have a transformation "pipeline" set up for several functions in a row.
Using |>
chaining you could write:
let createPerson n =
if n = 1 then "Homer" else "Someone else"
let hello name = "Hello " + name + "!"
let solution2 =
1
|> createPerson
|> hello
|> printf "%s"
The benefit of the pipe-backward operator <|
is that it changes operator precedence so it can save you a lot of brackets: Function arguments are normally evaluated left to right, using <|
you don't need the brackets if you want to pass the result of one function to another function - your example doesn't really take advantage of this.
These would be equivalent:
let createPerson n =
if n = 1 then "Homer" else "Someone else"
let hello name = "Hello " + name + "!"
let solution3 = hello <| createPerson 1
let solution4 = hello (createPerson 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With