I'm converting some F# code to OCaml and I see a lot of uses of this pipeline operator <|
, for example:
let printPeg expr =
printfn "%s" <| pegToString expr
The <|
operator is apparently defined as just:
# let ( <| ) a b = a b ;;
val ( <| ) : ('a -> 'b) -> 'a -> 'b = <fun>
I'm wondering why they bother to define and use this operator in F#, is it just so they can avoid putting in parens like this?:
let printPeg expr =
Printf.printf "%s" ( pegToString expr )
As far as I can tell, that would be the conversion of the F# code above to OCaml, correct?
Also, how would I implement F#'s <<
and >>
operators in Ocaml?
( the |>
operator seems to simply be: let ( |> ) a b = b a ;;
)
To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.
The conversion formula for a temperature that is expressed on the Celsius (°C) scale to its Fahrenheit (°F) representation is: °F = (9/5 × °C) + 32.
Looking to convert from Fahrenheit to Celsius? Estimate by working backwards using inverse operations! Take the temperature in Fahrenheit, subtract 30, and then divide the answer by 2.
why they bother to define and use this operator in F#, is it just so they can avoid putting in parens?
It's because the functional way of programming assumes threading a value through a chain of functions. Compare:
let f1 str server =
str
|> parseUserName
|> getUserByName server
|> validateLogin <| DateTime.Now
let f2 str server =
validateLogin(getUserByName(server, (parseUserName str)), DateTime.Now)
In the first snippet, we clearly see everything that happens with the value. Reading the second one, we have to go through all parens to figure out what's going on.
This article about function composition seems to be relevant.
So yes, in a regular life, it is mostly about parens. But also, pipeline operators are closely related to partial function application and point-free style of coding. See Programming is "Pointless", for example.
The pipeline |>
and function composition >>
<<
operators can produce yet another interesting effect when they are passed to higher-level functions, like here.
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