<div dir="rtl"><div dir="ltr">Hi,</div><div dir="ltr"><br></div><div dir="ltr">I've been digging around the source code of reactive-banana and I found this <a href="https://github.com/HeinrichApfelmus/reactive-banana/blob/master/reactive-banana/src/Reactive/Banana/Prim/Cached.hs">code</a>: <br><pre>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<br><br></pre><pre><font face="sans-serif">I'm trying to understand the reasom behind the use of <font face="monospace">mdo<font face="sans-serif">. Can't it be like this:<br></font></font></font></pre><pre><font face="sans-serif"><font face="monospace"><font face="sans-serif"><font face="monospace">do<br> a <- m<br> liftIO $ writeIORef key (Just a)<br> return a<br></font></font></font></font></pre><pre><font face="sans-serif"><font face="monospace"><font face="sans-serif"><font face="monospace"><font face="sans-serif">Removing the need for a recursive definition?<br><br></font></font></font></font></font></pre><pre><font face="sans-serif"><font face="monospace"><font face="sans-serif"><font face="monospace"><font face="sans-serif">Yotam<br></font></font></font></font></font></pre></div>
</div>