Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unfold tuple in OCaml

Tags:

ocaml

Is there any way to apply function to tuple members as function arguments? Or if not, can I anyhow create a function with arbitrary number of arguments and in its body apply some another function to the "tail" as it would be its arguments?

like image 919
Nutel Avatar asked Dec 20 '10 02:12

Nutel


2 Answers

In the general case, no. For the case of 2 arguments, you can use the curry and uncurry functions in the Batteries extensions to Pervasives.

It might be possible to cook something up with the Obj module, like the internals of printf do, but I would stay far far away from that. The difficulty is that the type system does not give you a way to express the type of a generalized curry or uncurry function. The type system does not let you "compute" over the length of a tuple - a 2-tuple is a 2-tuple and you don't have a way to express that (a*b*c) is really (a*b) with an additional component. printf has special support from the compiler to make the types work out properly, and it results in the function type being a part of the format type (so similar solutions won't work for tuples).

like image 164
Michael Ekstrand Avatar answered Nov 03 '22 01:11

Michael Ekstrand


The language itself does not allow you to define a function on tuples of arbitrary size.

It is however possible to define functions with an arbitrary number of arguments by following this folding technique (it's described there for SML but works equally well in OCaml).

like image 29
Daniel Bünzli Avatar answered Nov 02 '22 23:11

Daniel Bünzli