4 ms·
You are repeating what I said. I was defending the use of `unsafePerformIO` as a non-'hack', and perhaps I misunderstood you to be thinking otherwise. The memo
by applicative 16y ago
You are repeating what I said. I was defending the use of `unsafePerformIO` as a non-'hack', and perhaps I misunderstood you to be thinking otherwise. The memocombinators library uses Array, which uses `unsafePerformIO` and friends almost 700 times in one module. MemTrie takes a different approach, one not using unsafePerformIO; maybe I wasn't clear that was my meaning. In any case, there is little need for a library, at least for the simplest idea of memoization (the ugly Reddit discussion suggests there are many things to be meant.) It is just a case of writing down what is meant, as happens a few times in slightly different ways on the reddit page, off the top of peoples' heads. So for example this one:
memo :: Eq k => (k -> v) -> k -> v
memo f = unsafePerformIO $ do
ref <- newIORef [] :: IO (IORef [(k,v)]) -- make a page for a table
return $ \k -> unsafePerformIO $ do -- when f is applied to k
memotable <- readIORef ref -- get out the table
case lookup k memotable of -- see if k has been done
Just x -> return x -- if it has, we're done!
Nothing -> do -- if it hasn't
let a = f k -- calculate f k
atomicModifyIORef ref $ \t -> ((k,a):t,()) -- add it to the table before
return a -- returning f k
This is someone's brief treatment, which meets most of the definitions people were using. The clojure procedure is more powerful; as far as I can see, getting something similar in Haskell requires a bit more subtlety.