OCaml |> operator

守給你的承諾、 提交于 2019-12-03 11:03:04

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.

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!