Skip to content

Instantly share code, notes, and snippets.

@tmcl
Last active March 16, 2018 22:52
Show Gist options
  • Save tmcl/699e7b7c5d9a970ca95bad2d3a1c1f77 to your computer and use it in GitHub Desktop.
Save tmcl/699e7b7c5d9a970ca95bad2d3a1c1f77 to your computer and use it in GitHub Desktop.
Imperative Haskell
{-# 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