State monad in OCaml

Я пытался реализовать монаду состояния в OCaml (в качестве упражнения). Моя реализация выглядит так:

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;;

Я выбрал экзистенциальный тип для поля записи, так как мне не нравится идея использования функтора и обертывания типа состояния в модуле. Вышеупомянутая реализация работает, но я ran into a problem while implementing getState and setState. I tried to implement them like:

let getState = { state = fun s -> (s, s) }

let setState s = { state = fun _ -> ((), s) }

This doesn't work since the inferred field types, e.g. 'a -> ('a * 'a) and 'a -> (unit * 'a), are less generic than the declared type 's . 's -> ('a * 's). I understand why this is happening, but I was wondering if there is another way of making it work using the record approach?

Thanks.

Cheers, Alex

14
задан Alex 30 April 2011 в 18:24
поделиться