Function 在OCaml中隐藏函数参数而不使用类
我是一个OCaml初学者,所以这个问题可能不重要。我有以下几个功能:Function 在OCaml中隐藏函数参数而不使用类,function,functional-programming,ocaml,state,Function,Functional Programming,Ocaml,State,我是一个OCaml初学者,所以这个问题可能不重要。我有以下几个功能: 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 = ... ;; let rec f1状态=。。。 和 f2状态=。。。 和 f3状态=。。。 和 f4状态=。
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 = ...
;;
let rec
f1状态=。。。
和
f2状态=。。。
和
f3状态=。。。
和
f4状态=。。。
;;
这些函数中的每一个都以最后一个参数作为状态调用其他函数。因此,对于每个执行“树”,状态是一种全局只读变量。我如何以一种状态被抽象出来的方式来模拟它,而函数却可以访问它。请注意,我不想使用OCaml类,一个包含模块/子模块/函子的解决方案会很好
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
如果您希望“状态”是一个模块,例如:
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)
如果要将生成的fi
打包到模块中,请使用函子
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 ()...
干净、整洁、优雅!美好的