[Haskell-cafe] Troubles understanding memoization in SOE

Henning Thielemann lemming at henning-thielemann.de
Mon Sep 24 07:43:54 EDT 2007


On Sat, 22 Sep 2007, Peter Verswyvelen wrote:

> Hi,
>
> in SOE, the following memoization function is implemented:
>
> memo1 :: (a->b) -> (a->b)
> memo1 f = unsafePerformIO $ do
> cache <- newIORef []
> return $ \x -> unsafePerformIO $ do
>             vals <- readIORef cache
>             case x `inCache` vals of
>               Nothing -> do let y = f x
>                             writeIORef cache [(x,y)] -- ((x,y) : -- 
> if null vals then [] else [head vals])
>                             return y
>               Just y  -> do return y

Hm, why the unsafePerformIO hacks? It should be possible without:
   http://www.haskell.org/haskellwiki/Memoization


More information about the Haskell-Cafe mailing list