Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Laws hold? MonadFix (Codensity m) #64

Open
Icelandjack opened this issue Oct 17, 2020 · 2 comments
Open

Laws hold? MonadFix (Codensity m) #64

Icelandjack opened this issue Oct 17, 2020 · 2 comments

Comments

@Icelandjack
Copy link
Contributor

The library mmtl has a MonadFix (Codensity m) instance

-- still need to prove that MonadFix laws hold
instance MonadFix m => MonadFix (Codensity m) where
    mfix :: (a -> Codensity m a) -> Codensity m a
    mfix f = lift (mfix (lowerCodensity . f))

https://hackage.haskell.org/package/mmtl-0.1/docs/Control-Monad-Codensity.html

@paf31
Copy link

paf31 commented Dec 14, 2020

I'm using Codensity to ensure timely resource cleanup (like a transformer version of the managed library), in which case this is not going to be the instance you want, since it will run your finalizers early, as you exit the mdo block.

Another option is to use a lazily-evaluated promise for the result, mirroring the approach in fixIO:

fixCodensity :: MonadIO m => (a -> Codensity m a) -> Codensity m a
fixCodensity f = Codensity \k -> do
  promise <- liftIO $ IORef.newIORef (error "result eval'd too early")
  ans <- liftIO $ unsafeDupableInterleaveIO (IORef.readIORef promise)
  runCodensity (f ans) \a -> do
    liftIO $ IORef.writeIORef promise a
    k a

This is also probably not the instance you'd want in a general-purpose library, but I figured I'd put it here for reference.

@Mathnerd314
Copy link

There's also an implementation here: https://stackoverflow.com/questions/25827227/why-cant-there-be-an-instance-of-monadfix-for-the-continuation-monad

instance MonadFix m => MonadFix (Codensity m) where
  mfix f = Codensity (\ka -> mfixing (\a -> runCodensity (f a) ka<&>(,a)))
    where mfixing f = fst <$> mfix (\ ~(_,a) -> f a )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants