Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting F# pipeline operators ( <|, >>, << ) to OCaml

Tags:

inline

f#

ocaml

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 ;; )

like image 415
aneccodeal Avatar asked Jan 19 '13 03:01

aneccodeal


People also ask

How do you convert C to F easily?

To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

What is Fahrenheit formula?

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.

How do you convert F to C mentally?

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.


1 Answers

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.

like image 200
bytebuster Avatar answered Oct 02 '22 19:10

bytebuster