How do you implement in OCaml the operator
mfix : ('a -> 'a state_monad) -> 'a state_monad
for a state monad? (Since it relies heavily on laziness, I guess one has to use the Lazy module from the standard library).
More precisely:
assuming a signature with
type 'a t
( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
mfix
is the least fixpoint of the equation: mfix f = mfix f >>= f
But if you define it simply as
let rec mfix f = mfix f >>= f
you end up with looping recursion due to the strict semantics of OCaml as opposed to the lazy semantics of Haskell.
Take for instance
type 'a t = 'a list
let ( >>= ) m f = List.flatten (List.map f m)
then for example
let _ = mfix (fun _ -> [])
leads to a stack overflow while I would like it to be []
.
I guess there is a way to overcome this using the Lazy module of the standard library but I cannot find how.