3

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!

1 Answer 1

6
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 ()...
1
  • Clean, neat and elegant! Nice!
    – user34812
    Commented May 8, 2014 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.