Advertisement
Guest User

Untitled

a guest
Aug 8th, 2015
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Control.Monad.ST
  2. import Control.Monad.Reader
  3. import qualified Data.HashTable.ST.Basic as H
  4.  
  5. type HT s = H.HashTable s Int Int
  6. type CST s = ReaderT (HT s) (ST s)
  7.  
  8. fibCore :: Int -> Int -> CST s Int
  9. fibCore n base = do
  10.   if (n == 1) || (n == 2)
  11.     then return 1
  12.     else do
  13.       u <- fibCoreCached (n - 1) base
  14.       v <- fibCoreCached (n - 2) base
  15.       return (mod (u + v) base)
  16.  
  17. fibCoreCached :: Int -> Int -> CST s Int
  18. fibCoreCached n base = do
  19.   cache <- ask
  20.   x <- lift (H.lookup cache n)
  21.   case x of
  22.     Just t -> return t
  23.     Nothing -> do
  24.       r <- fibCore n base
  25.       lift (H.insert cache n r)
  26.       return r
  27.  
  28. fib :: Int -> Int -> Int
  29. fib n base = runST $ do
  30.   cache <- H.new
  31.   (flip runReaderT) cache $ fibCoreCached n base
  32.  
  33. main :: IO()
  34. main = putStrLn (show (fib 10000000 999983))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement