Thanks to reactions!

What do you think about such a function? This function is
still a bit dangerous (I think). I don't know how to make
sure the compiler does not lift cache to something global.

But on the other hand this use of unsafePerformIO is legit
because it doesn't alter the referential transparency of 
the function. The same as in DiffArray.

Greetings
Gerben

memo f =
  let cache = unsafePerformIO $ newIORef M.empty
      cachedFunc x = unsafePerformIO (do
                       m <- readIORef cache
                       case M.lookup x m of
                         Just y -> return y
                         Nothing -> do let res = f x
                                       writeIORef cache $ M.insert x res m
                                       return res)
  in cachedFunc

memo2 f = curry $ memo $ uncurry f

-- 
View this message in context: 
http://www.nabble.com/memoization-tp25306687p25381881.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to