Why do you prefer to correct arguments in OCaml?

"Introduction to Caml" reports

Note: in Caml, it is better to use Curried function definitions for functions with multiple arguments, rather than tuples.

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

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

Why is currying recommended for OCaml function declarations on tuple arguments? Is this more flexibility for currying / partial evaluation, or is there any other benefit that comes from the implementation details of the OCaml compiler?

+6
source share
3 answers

Yes, it is mainly notational convenience and flexibility for partial use. Curried functions are idiomatic in OCaml, and the compiler is likely to optimize them slightly better than interleaved functions (whereas SML compilers usually optimize for tuples).

The pluses of tupling are the symmetry of the argument / result you mentioned (which is especially useful when compiling functions) and, possibly, an innovative acquaintance (at least for people arriving from a non-functional world).

+2
source

I think that many of them are consistent with the standard library functions in OCaml, and in standard ML they, as a rule, do not exclude some functions of a higher order. However, there is one difference that is baked in the language: operators (for example, (*) ) are in OCaml (for example, int -> int -> int ); whereas they are not loaded into standard ML (for example, op* can be (int * int) -> int ). Because of this, higher-order built-in functions (for example, fold) also perform a function that is in OCaml and not loaded in standard ML; this means that in order for your function to work with this, you need to follow the corresponding agreement, and it follows from there.

+5
source

Some comments about optimization in OCaml.

In OCaml, I noticed that tuples always stand out when passing them as an argument. Even if the allocation in the primary heap happens quickly in ocaml, this is of course more than doing nothing. Thus, every time you pass a tuple as an argument, it takes some time to distribute and populate the tuple.

I was expecting the ocaml compiler to optimize cases where there is no need to build a tuple. For example, when you embed a called function, you can use only the components of the tuple, not the tuple itself. Thus, the tuple can simply be ignored. Unfortunately, in this case, OCaml does not delete the useless tuple and still performs the selection. For this reason, it is not recommended to use tuples in critical sections of code.

+1
source

Source: https://habr.com/ru/post/916163/


All Articles