use*_*812 3 state ocaml functional-programming function
我是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 = ...
;;
Run Code Online (Sandbox Code Playgroud)
这些函数中的每一个都使用最后一个参数作为状态调用其他函数.因此,对于每个执行'树',state是一种全局只读变量.如何以抽象出状态的方式模拟这个,但函数可以访问它.请注意,我不想使用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
Run Code Online (Sandbox Code Playgroud)
如果您希望"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)
Run Code Online (Sandbox Code Playgroud)
如果您希望将结果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 ()...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |