Is it possible to implement MonadFix for `Free`?

前端 未结 3 1299
無奈伤痛
無奈伤痛 2020-12-30 00:13

http://hackage.haskell.org/package/free in Control.Monad.Free.Free allows one to get access to the \"free monad\" for any given Functor. It does n

3条回答
  •  庸人自扰
    2020-12-30 01:09

    No, it cannot be written in general, because not every Monad is an instance of MonadFix. Every Monad can be implemented using the FreeMonad underneath. If you could implement the MonadFix for Free, then you would be able to derive MonadFix from any Monad, which is not possible. But of course, you can define a FreeFix for the MonadFix class.

    I think it might look somehow like this, but this is just a 3rd guess (still not tested):

    data FreeFix m a = FreeFix { runFreeFix :: (forall r. (r -> m r) -> m r) -> m a }
    
    instance (Monad m) => Monad (FreeFix m) where
        return a = FreeFix $ \_-> do
            return a
        f >>= g = FreeFix $ \mfx -> do
            x <- runFreeFix f mfx
            runFreeFix (g x) mfx
    
    instance (Monad m) => MonadFix (FreeFix m) where
        mfix f = FreeFix $ \mfx -> do
            mfx (\r->runFreeFix (f r) mfx)
    

    The idea is that m is a Monad that lacks an implementation for mfix; so mfix needs to be a parameter when FreeFix will be reduced.

提交回复
热议问题