Jane Street Interview Question

Implement a function `memoize : (a -> b) -> (a -> b)`

Interview Answers

Anonymous

Apr 27, 2015

I got stuck a bit before I figured out that I cannot do it in Haskell easily and safely and I was unsure about using unsafe features or monads. So I just switched to JavaScript. I coded my memoization function to set up a lexically scoped hash-based cache of function results plus an inner closure using this cache.

Anonymous

Feb 25, 2016

So. Here is a Haskell answer which works for me. I think adding the Ord constraint is relatively minor. This ought to be a correct use of unsafePerformIO... import Data.Map import Data.IORef import System.IO.Unsafe memoize :: Ord a => (a -> b) -> (a -> b) memoize f = \x -> unsafePerformIO $ do table return y Nothing -> do let y = f x modifyIORef dict (insert x y) return y where dict :: IORef (Map a b) {-# NOINLINE dict #-} dict = unsafePerformIO $ newIORef empty