OCaml |> operator

只谈情不闲聊 提交于 2019-12-21 03:22:11

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/30493644/ocaml-operator

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