[Haskell-cafe] Memo + IORef

Benja Fallenstein benja.fallenstein at gmail.com
Sat Jun 16 07:17:42 EDT 2007

Hi Tony,

2007/6/16, Tony Morris <tmorris at tmorris.net>:
> I was told on #haskell (IRC) the other day that it is possible to write
> a general memoisation table using IORef and unsafePerformIO. I can't
> think of how this can be achieved without writing to a file, since a
> function cannot hold state between invocations. What am I missing?

You create a single IORef for the function (via unsafePerformIO), for
example like this:

memoTable :: Map Int Int
memoTable = unsafePerformIO $ newIORef Map.empty

memoizedFactorial n = unsafePerformIO $ do
    tbl <- readIORef memoTable
    if (n `Map.member` tbl) then return (tbl Map.! n) else do
        let r = if n == 0 then 1 else n * memoizedFactorial (n-1)
        writeIORef memoTable $ Map.insert n r tbl
        return r

- Benja

More information about the Haskell-Cafe mailing list