Question

I am an OCaml beginner so this question might be trivial. I have a few functions like this:

let rec
f1 <list of args> state = ...
and
f2 <list of args> state = ...
and
f3 <list of args> state = ...
and
f4 <list of args> state = ...
;;

Each of these functions call the other functions with the last argument as state. Therefore, for each execution 'tree', state is a kind of global read-only variable. How can I simulate this in a manner that state is abstracted out, yet the functions have access to it. Note that I don't want to use OCaml classes, a solution involving modules/submodules/functors would be nice!

Was it helpful?

Solution

let share state = 
  let rec f1 ... = ... you can use state freely here ...
  and f2 ...     = ... same here ...  
  and f3 ...     = ... same here ...
  and f4 ...     = ... same here ...
  in
  f1, f2, f3, f4

let state = ...
let f1, f2, f3, f4 = share state 

If you want "state" to be a module that would be for example:

module type S = sig ... end

let share m =
  let module M = (val m : S) in 
  let rec f1 ... = ... use M at will ...
  and f2 ...     = ... use M at will ...
  and f3 ...     = ... use M at will ...
  and f4 ...     = ... use M at will ...
  in 
  f1, f2, f3, f4


module M : S = struct ... end 

let f1, f2, f3, f4 = share (module M)

If you want the resulting fi to be packed in a module then use a functor

module type S = sig  
  val f1 : ...
  val f2 : ...
  val f3 : ...
  val f4 : ...
end

module type State : sig ... end

module Make (M : State) : S = struct 
  let rec f1 ... = ... use M at will here ...
  and f2 ...     = ... again ...
  and f3 ...     = ... again ... 
  and f4 ...     = ... again ...
end

module State : State = struct ... implement state... end 
module Instance = Make (State) 

let () = Instance.f1 ()...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top