generic timer high-order function in OCaml
generics, ocaml
Solution
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:
let timer f x =
let t0 = Sys.time()
in let result = f x
in let diff = Sys.time() -. t0
in diff, result
Since any function `g` with any arity can be passed to `timer` easily by:
let diff, result = timer (fun () -> g x1 x2 x3 ... xN) ()
or better by using partial application (as suggested by @Andreas):
let diff, result = timer (g x1 x2 x3 ... xN-1) xN
Problem
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 * 'r` where the float would be a metric of the time spent in the function (e.g. reported by `Sys.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.