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:
After playing with that and failing I ended up with a less than ideal solution. Given a Maybe monad like below:
I created a state transformer monad which take an argument of type m:MaybeBuilder
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:
If anyone has an idea how I can make this work I would love to hear it.