Why do some OCaml functions take () as a parameter?

时光毁灭记忆、已成空白 提交于 2019-12-06 19:03:04

问题


Example in Unix module:

val environment : unit -> string array

Why not just:

val environment : string array

?


回答1:


Because it denotes a function that takes a value of type unit as its parameter. The unit type is only inhabited by the value "()". This is usually used to mean that the function is going to perform some kind of IO or induce a side-effect, and needs no input. The second type signature you provided is the signature for a value, not a function that can be applied. If some expression were bound to this name, that expression would be evaluated at the time the value binding takes place, not at the time it is referenced (as is the case with function application).




回答2:


The unit () parameter is similar to a void parameter in C. It denotes a function that does not use its argument to compute something.

In your example, the environment can be changed by the program, so it cannot just be a static value computed at the beginning of the program, but at the same time, its value does not depend on its argument.

For example:

let e1 = Unix.environment ();;
Unix.putenv "USER" "somebody_else";;
let e2 = Unix.environment ();;
e1 = e2;;

And you can see that e1 and e2 are different, so Unix.environment cannot just be of type (string * string) array, but needs to be a function.




回答3:


If you were in a lazy language, such as Haskell, with no side effects and objects being evaluated only when needed, there would be no need for these dummy arguments.

In OCaml, requiring an argument of type unit (whose only value is ()) serves to freeze the computation until the argument is supplied. In this case, it freezes the computation until Unix.environment () is to be computed — which is especially important since it can have different values throughout time (again, OCaml has side effects).



来源:https://stackoverflow.com/questions/3494668/why-do-some-ocaml-functions-take-as-a-parameter

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