Skip to content

Instantly share code, notes, and snippets.

@KPCCoiL
Created June 3, 2014 06:28
Show Gist options
  • Save KPCCoiL/c80e7629d92f4524190a to your computer and use it in GitHub Desktop.
Save KPCCoiL/c80e7629d92f4524190a to your computer and use it in GitHub Desktop.
memoization in Haskell
import qualified Data.Map as M
import Data.Map ((!))
fib :: Integer -> Integer
fib n = fst $ fib_aux M.empty n
fib_aux mp 0 = (1,mp)
fib_aux mp 1 = (1,mp)
fib_aux mp n | M.member n mp = (mp!n,mp)
| otherwise = (next,nmp)
where
(n1,mp1) = fib_aux mp (n-1)
(n2,mp2) = fib_aux mp1 (n-2)
next = n1+n2
nmp = M.insert n next mp2
main = readLn >>= print . fib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment