[Haskell-cafe] Caching Actions

Yotam Ohad yotam2206 at gmail.com
Thu Jan 25 09:50:18 UTC 2018


Hi,

I've been digging around the source code of reactive-banana and I found
this code
<https://github.com/HeinrichApfelmus/reactive-banana/blob/master/reactive-banana/src/Reactive/Banana/Prim/Cached.hs>:


data Cached m a = Cached (m a)

runCached :: Cached m a -> m a
runCached (Cached x) = x

-- | An action whose result will be cached.
-- Executing the action the first time in the monad will
-- execute the side effects. From then on,
-- only the generated value will be returned.
{-# NOINLINE cache #-}
cache :: (MonadFix m, MonadIO m) => m a -> Cached m a
cache m = unsafePerformIO $ do
    key <- liftIO $ newIORef Nothing
    return $ Cached $ do
        ma <- liftIO $ readIORef key    -- read the cached result
        case ma of
            Just a  -> return a         -- return the cached result.
            Nothing -> mdo
                liftIO $                -- write the result already
                    writeIORef key (Just a)
                a <- m                  -- evaluate
                return a

I'm trying to understand the reasom behind the use of mdo. Can't it be
like this:

do
  a <- m
  liftIO $ writeIORef key (Just a)
  return a

Removing the need for a recursive definition?

Yotam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180125/e9f685d4/attachment.html>


More information about the Haskell-Cafe mailing list