Last active
August 29, 2015 14:12
-
-
Save evansb/c0b959a1f5ea95379c72 to your computer and use it in GitHub Desktop.
Memoization hack in Haskell, using unsafe IO operation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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