Last active
March 16, 2018 22:52
-
-
Save tmcl/699e7b7c5d9a970ca95bad2d3a1c1f77 to your computer and use it in GitHub Desktop.
Imperative Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE UnicodeSyntax #-} | |
module Main | |
where | |
import Control.Monad.ST | |
import Data.STRef | |
import Prelude.Unicode -- from base-unicode-symbols | |
import System.Environment | |
import Control.Monad.Loops | |
fib ∷ ℤ → ℤ | |
fib n = runST $ do | |
a ← newSTRef 0 | |
b ← newSTRef 1 | |
counter ← newSTRef 1 | |
whileM_ ((< n) <$> readSTRef counter) $ do | |
oldA ← readSTRef a | |
writeSTRef a =<< readSTRef b | |
modifySTRef' b (+ oldA) | |
modifySTRef' counter (+ 1) | |
readSTRef b | |
run ∷ [String] → IO () | |
run [n] = print $ fib (read n) | |
run _ = error "I want one number n, and will give the nth fibonacci number" | |
main ∷ IO () | |
main = getArgs >>= run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment