13
我试图在OCaml中实现状态monad(作为练习)。我的实现看起来是这样的:OCaml中的状态monad
module type MONAD_BUILDER =
sig
type 'a t
val return : 'a -> 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
end;;
module MonadBuilder = functor (M: MONAD_BUILDER) ->
struct
let (>>=) = M.bind
let return = M.return
end;;
module StateM =
struct
type 'a state = { state: 's . 's -> ('a * 's) }
type 'a t = 'a state
let return x = { state = fun s -> (x, s) }
let bind m f =
let aux s =
let (x, s') = m.state s in
(f x).state s'
in { state = aux }
let run m x = fst (m.state x)
end;;
我选择的是生存型的记录字段,因为我不喜欢使用仿函数和包装模块中的状态类型的想法。上面的实现工作,但我 遇到一个问题,同时实施getState
和setState
。我试图执行它们,如:
let getState = { state = fun s -> (s, s) }
let setState s = { state = fun _ -> ((), s) }
由于推断的字段类型(例如, 'a -> ('a * 'a)
和'a -> (unit * 'a)
,不如声明的类型's . 's -> ('a * 's)
通用。我明白为什么会发生这种情况,但我想知道是否有另一种使用记录方法使其工作的方式?
谢谢。
干杯, 亚历
感谢您的回答。 – Alex 2011-05-01 13:42:43