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,
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. This lets you build up something that looks like a Unix pipeline:
# let ( |> ) x f = f x;;
val ( |> ) : 'a -> ('a -> 'b) -> 'b = <fun>
# 0.0 |> sin |> exp;;
- : float = 1.
The notation Module.(expr)
is used to open the module temporarily for the one expression. In other words, you can use names from the module directly in the expression, without having to prefix the module name.
The |>
operator looks like the |
in bash.
The basic idea is that
e |> f = f e
It is a way to write your applications in the order of execution.
As an exemple you could use it (I don't particularly think you should though) to avoid lets:
12 |> fun x -> e
instead of
let x = 12 in e
For the Module.()
thing, it is to use a specific function of a given module.
You probably have seen List.map
before.
You could of course use open List
and then only refer to the function with map
. But if you also open Array
afterwards, map
is now referring to Array.map
so you need to use List.map
.
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.