[Haskell-cafe] memoization
staafmeister
g.c.stavenga at uu.nl
Thu Sep 10 07:54:34 EDT 2009
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.
More information about the Haskell-Cafe
mailing list