Why prefer currying to tuple arguments in OCaml?

痴心易碎 提交于 2019-12-12 10:37:10

问题


"Introduction to Caml" says

Note, in Caml it is better to use Curried function definitions for multiple-argument functions, not tuples.

when comparing 'a -> 'b -> 'c calling conventions to 'a * 'b -> 'c.

When working with SML/NJ I got used to using tuple types for both input and output : ('a * 'b) -> ('c * 'd) so using tuples to express multiple inputs seems symmetric with the way I express multiple outputs.

Why is currying recommended for OCaml function declarations over tuple arguments? Is it just the greater flexibility that comes with allowing currying/partial evaluation, or is there some other benefit that derives from implementation details of the OCaml compiler?


回答1:


Yes, it is mainly the notational convenience and the flexibility to do partial application. Curried functions are idiomatic in OCaml, and the compiler is likely to optimise them somewhat better than tupled functions (whereas SML compilers typically optimise for tuples).

The pros of tupling are the argument/result symmetry you mention (which is especially useful when composing functions) and perhaps the notational familiarity (at least for people coming from the non-functional world).




回答2:


I think a lot of it is convention -- standard library functions in OCaml are curried, whereas in Standard ML they are generally not except for some higher-order functions. However, there is one difference baked into the language: the operators (e.g. (*)) are curried in OCaml (e.g. int -> int -> int); whereas they are uncurried in Standard ML (e.g. op* can be (int * int) -> int). Because of that, built-in higher-order functions (e.g. fold) also take a function that is curried in OCaml and uncurried in Standard ML; that means for your function to work with that, you need to follow the respective convention, and it follows from there.




回答3:


Some comment about the optimisation in OCaml.

In OCaml, i noticed that tuples are always allocated when passing them as argument. Even if allocating in the primary heap is fast in ocaml, it is of course longer than doing nothing. Thus each time you pass a tuple as argument, there is some time spent to the allocation and filling of the tuple.

I expected that the ocaml compiler would be optimizing cases where it isn't needed to build the tuple. For instance, when you inline the called function, you may only use the tuple components and not the tuple itself. Thus the tuple could just be ignored. Unfortunately in this case OCaml doesn't remove the useless tuple and still perform the allocation. For this reason, it may not be a good idea to use tuples in critical sections of code.



来源:https://stackoverflow.com/questions/10666913/why-prefer-currying-to-tuple-arguments-in-ocaml

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