Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml |> operator

Tags:

Could someone explain what the |> operator does? This code was taken from the reference here:

let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world") 

I can see what it does, but I wouldn't know how to apply the |> operator otherwise.

For that matter, I have no idea what the Module.() syntax is doing either. An explanation on that would be nice too.

like image 885
eatonphil Avatar asked May 27 '15 21:05

eatonphil


People also ask

What does |> do in OCaml?

The |> operator represents reverse function application. It sounds complicated but it just means you can put the function (and maybe a few extra parameters) after the value you want to apply it to.

What is the operator in OCaml?

Comparisons (Relational Operators) Most of these operators will look familiar: =, <>, <, <=, >, >=. OCaml distinguishes between structural equality and physical equality (essentially equality of the address of an object). = is structural equality and == is physical equality. Beware: <> is structural not-equals while !=

What does :: mean in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.

How Use let in OCaml?

The value of a let definition is the value of it's body (i.e. expr2). You can therefore use a let anywhere OCaml is expecting an expression. This is because a let definition is like a syntactially fancy operator that takes three operands (name, expr1 and expr2) and has a lower precedence than the arithmetic operators.


1 Answers

Module.(e) is equivalent to let open Module in e. It is a shorthand syntax to introduce things in scope.

The operator |> is defined in module Pervasives as let (|>) x f = f x. (In fact, it is defined as an external primitive, easier to compile. This is unimportant here.) It is the reverse application function, that makes it easier to chain successive calls. Without it, you would need to write

let m = PairsMap.(add (1,0) "world" (add (0,1) "hello" empty)) 

that requires more parentheses.

like image 92
byako Avatar answered Sep 25 '22 12:09

byako