【问题标题】:Hiding function parameters in OCaml without using classes在 OCaml 中隐藏函数参数而不使用类
【发布时间】:2014-06-25 20:44:22
【问题描述】:

我是 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 = ...
;;

这些函数中的每一个都以最后一个参数作为状态调用其他函数。因此,对于每个执行“树”,状态都是一种全局只读变量。我如何以抽象出状态的方式模拟它,但函数可以访问它。请注意,我不想使用 OCaml 类,涉及模块/子模块/函子的解决方案会很好!

【问题讨论】:

    标签: function functional-programming ocaml state


    【解决方案1】:
    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 ()...
    

    【讨论】:

    • 干净、整洁、优雅!不错!
    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多