I have a recursive function
fact, which can be called from either an expression inside it or an expression outside it.
I would like to associate
fact with a variable
v, such that each time
fact is called from outside (another function),
v is initialized, and its value can be changed inside
fact, but never can be initialized when
fact is called from inside.
The following code suits my need, but one problem is that
v is defined as a global variable, and I have to do
v := init before calling
fact from outside, which I do not find beautiful.
let init = 100 let v = ref init let rec fact (n: int) : int = v := !v + 1; if n <= 0 then 1 else n * fact (n - 1) let rec fib (n: int) : int = if n <= 0 then 0 else if n = 1 then (v := !v + 50; 1) else fib (n-1) + fib (n-2) let main = v := init; print_int (fact 3); print_int !v; (* 104 is expected *) v := init; print_int (fib 3); print_int !v;; (* 200 is expected *)
Could anyone think of a better implementation?