Skip to content

Instantly share code, notes, and snippets.

@evansb
Last active August 29, 2015 14:12
Show Gist options
  • Save evansb/c0b959a1f5ea95379c72 to your computer and use it in GitHub Desktop.
Save evansb/c0b959a1f5ea95379c72 to your computer and use it in GitHub Desktop.
Memoization hack in Haskell, using unsafe IO operation.
module Memoize (memoize) where
import Debug.Trace
import Data.Hashable
import System.IO.Unsafe
import qualified Data.HashTable.IO as H
type HashTable k v = H.CuckooHashTable k v
memoize :: (Eq k, Hashable k) => (k -> a) -> k -> a
memoize f = unsafePerformIO $ do
cache <- H.new :: IO (HashTable k v)
return $ \x -> unsafePerformIO $ do
tryV <- H.lookup cache x
case tryV of
Nothing -> do
traceM "New value"
let v = f x
H.insert cache x v
return v
Just v -> return v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment