我想編寫一些代碼來構建一些使用本地狀態的東西。例如,考慮使用本地狀態產生連續整數下面的代碼:在OCaml中是否有一種慣用的方式來實現隱式本地狀態?
type state = int ref
let uniqueId : (state -> int) =
fun s -> incr s; !s
let makeThings : ((state -> 'a) -> 'a) =
fun body -> body (ref 0)
let() =
let x1 = makeThings(fun s ->
let i = uniqueId s in (* 1 *)
i
) in
print_int x1; print_newline(); (* Prints 1 *)
(* Each makeThings callback gets its own local state.
The ids start being generated from 1 again *)
let x2 = makeThings(fun s ->
let i = uniqueId s in (* 1 *)
let j = uniqueId s in (* 2 *)
i + j
) in
print_int x2; print_newline(); (* Prints 3 *)
()
我很好奇,如果有一種方法,使該makeThings內s
狀態參數回調隱式的,所以我就不說了需要反覆輸入,因此保證所有uniqueId
調用都通過相同的狀態參數。例如,在哈斯克爾你可以使用單子做,符號與沿
makeThings $ do
i <- uniqueId
j <- uniqueId
return (i + j)
線OCaml中,浮現在我的腦海裏的唯一的東西代碼落得正在s
一個全局變量(萬劫)或者試圖模仿Haskell的monadic接口,我擔心這會導致很多工作,並且由於缺少標識符而導致代碼編寫慢也很難看。有沒有我沒有想到的替代方案?
獲得你的問題是有點不明確,espcially你在你的腦海中提到'使SA全球variable',而是在利奧白您的評論你說你不希望全球變化。我想你想達到的是: '1。具有狀態的函數f(make_things)。 2.每次調用f時,狀態都會被重置 3.但是在一次調用f的過程中,狀態可以自動改變。 '我的猜測是正確的嗎? – 2014-10-07 16:00:02