Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any methods for recovering enough laziness to tie the knot in a monad?

I want to write a slick bit of code (saving me much time to implement otherwise) by tying the knot. It goes roughly like this,

n <- myinstr n x

where in theory, myinstr should run x to get a value, which will become n. myinstr, which runs inside a State monad, will put n into the state, but this doesn't affect x's computation.

I've tried using DoRec and a naiive implementation of mfix,

instance Monad 𝔪 => MonadFix (MyMonad 𝔪) where
    mfix f = fix (\mx -> mx >>= f)

but things freeze. Are there any methods for fixing my code (or methodologies for designing it correctly the first time) or should I write something more straightforward?

like image 461
gatoatigrado Avatar asked Dec 05 '11 00:12

gatoatigrado


1 Answers

There is no generic way to make an arbitrary monad an instance of MonadFix. The actual code depends on the monad, and it's not even possible for all monads. You can look at the various monads to see how it's done. And if your monad is in fact State there should already be an instance.

like image 66
augustss Avatar answered Nov 06 '22 13:11

augustss