I have have been playing around with F# and I decided to create a state monad. This worked out really well since I was able to leverage the F# computation expressions. I then decided to try to extend this and make it more general by creating a parameterized state transformer monad. This is a state monad which encapsulates another monad. What this allow you to do is turn any computation into a statefull one.
This concept exists in Haskell which you can see here. However, my attempts at replicating this in F# failed. Unlike in Haskell, the computation expressions in F# don’t share a common interface (or type class). This prevents a computation from being able to generically take another computation as a parameter. The reason is that an operation on the parameterized state transformer monad such as bind will result in a bind called on its encapsulated monad. But since there is no interface for computations there is no bind method to call.
I attempted to fix this by creating my own monad interface but this didn’t work:
type Monad = abstract Bind : 'm * ('a -> 'm) -> 'm abstract Delay : (unit ->'m) -> 'm abstract Let : 'a * ('a -> 'm) -> 'm abstract Return : 'a -> 'm abstract Zero : unit -> 'm abstract Combine : 'm -> 'm2 -> 'm3 abstract Run : (unit ->'m) -> 'm
After playing with that and failing I ended up with a less than ideal solution. Given a Maybe monad like below:
// Maybe Monad type MaybeBuilder() = member b.Return(x) = Some x member b.Run(f) = f() member b.Delay(f) = f member b.Let(p,rest) = rest p member b.Zero () = None member b.Combine(m1,dm2) = match m1 with | None -> dm2() | x -> x member b.Bind(p,rest) = match p with | None -> None | Some r -> rest r
I created a state transformer monad which take an argument of type m:MaybeBuilder
type StateMBuilder(m:MaybeBuilder) = member b.Return(x) = fun s -> m.Return (x,s) member b.Run(f) = fun inp -> (f inp)() member b.Delay(f) = fun inp -> fun () -> f() inp member b.Let(p,rest) = rest p member b.Zero () = fun s -> m.Zero() member b.Bind(p,rest) = fun s -> m.Bind(p s,fun (v,s2) -> rest v s2) member b.Combine(p1,dp2) = fun s -> m.Combine(p1 s, dp2 s) // State specific functions member b.Update f = fun s -> try m.Return (s, f s) with e -> m.Zero() member b.Read () = b.Update id member b.Set t = b.Update (fun _ -> t)
Now although this type is technically parameterized ;) it isn’t really the idea since its not generic, it has to be a MaybeBuilder. To use this with a different monad I would need to change m:MaybeBuild to m:SomeOtherMonad.
I am still going to play with this but this is as far as I have gotten.
After all of that here is how you create a state transformer monad parameterized over the maybe monad:
let maybe = MaybeBuilder() let state = StateMBuilder(maybe)
If anyone has an idea how I can make this work I would love to hear it.