2014-05-08 48 views
3

我是一個OCaml初學者,所以這個問題可能是微不足道的。我有幾個這樣的功能:在不使用類的情況下隱藏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類,涉及modules/submodules/functors的解決方案會很好!

回答

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 

如果你想「狀態」是這將是例如一個模塊:

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()... 
+0

清潔,整潔,優雅!太好了! – user34812

相關問題