Nutel
Nutel

Reputation: 2294

Unfold tuple in 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?

Upvotes: 5

Views: 1957

Answers (2)

Daniel Bünzli
Daniel Bünzli

Reputation: 5167

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).

Upvotes: 7

Michael Ekstrand
Michael Ekstrand

Reputation: 29090

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).

Upvotes: 7

Related Questions