I am trying to implement a generic timer function in OCaml which will take as input a function of arbitrary arity and return type ‘r and returns a function with:
- the same arity and types of input parameters
, and - return type
float * 'rwhere the float would be a metric of the time spent in the function (e.g. reported bySys.time())
The problem is I can’t implement it in such a way that it can handle functions of any arity. E.g. the following code:
let timer f =
let timerf x y =
let t0 = Sys.time ()
in let result = f x y
in let diff = Sys.time() -. t0
in diff, result
in timerf
works only with functions of input arity 2. It is not obvious to me how to generalize it to handle functions of any arity. I was hoping the partial function applications would somehow magically solve the conundrum but I can’t get it to work.
I understand your intention of making a timer function with arbitrary arity. But you cannot do it in an easy way in OCaml.
Moreover, a timer function with only one param is enough for use in practice:
Since any function
gwith any arity can be passed totimereasily by:or better by using partial application (as suggested by @Andreas):