Gurg Hackpof
Gurg Hackpof

Reputation: 1334

How to supply function arguments from a list?

Assume I have a function f that takes n arguments of the same type f: 'a * 'a * ... * 'a -> 'b

Assume I have a list lof n 'a elements,

Does the functor call_function_with_list exist? It would mean this: call_function_with_list f l = f l[0] l[1] ... l[n-1]

Observe that I am not interested in specifying a particular call_function_with_list for a fixed number n (which could be done quite simply) but I am interested in having a general call_function_with_list that works for all n

Upvotes: 1

Views: 83

Answers (1)

Virgile
Virgile

Reputation: 10148

You can't (without resorting to the dark magic of the Obj module, that is). Indeed, there are two issues. First OCaml's type system cannot represents something like 'a list -> ('a * 'a * ... * 'a) where ... actually depends on the length of the argument (you could do something like that in Coq for instance). Second, in OCaml an n-uple is not an iterated version of a pair, i.e. a value of type 'a * 'a * 'a is neither a value of type 'a * ('a * 'a) nor of type ('a * ('a * 'a)), so that you cannot build your nuple step by step from the elements of the list.

# let x = (1,2,3);;
val x : int * int * int = (1, 2, 3)
# let y = (1,(2,3));;
val y : int * (int * int) = (1, (2, 3))
# let z = (1,2),3;;
val z : (int * int) * int = ((1, 2), 3)
# x = y;;
Error: This expression has type int * (int * int)
       but an expression was expected of type int * int * int
# x = z;;
Error: This expression has type (int * int) * int
       but an expression was expected of type int * int * int

Upvotes: 4

Related Questions