Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I declare pipelines?

Tags:

f#

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?

like image 601
ebb Avatar asked Dec 28 '22 00:12

ebb


1 Answers

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)
like image 71
BrokenGlass Avatar answered Dec 30 '22 12:12

BrokenGlass