Pergunta de entrevista da empresa Jane Street

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

Respostas da entrevista

Sigiloso

27 de abr. de 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.

Sigiloso

25 de fev. de 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