Last active
December 15, 2015 02:49
-
-
Save NeilRobbins/5190365 to your computer and use it in GitHub Desktop.
Fizzbuzz in Haskell - just because
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
import System.Environment | |
main = do (countTo:_) <- getArgs | |
let numbers = fizzbuzz [0..(read countTo)] | |
mapM_ putStr $ map (\n -> n ++ ", ") $ init numbers | |
putStrLn $ last numbers | |
divides d n = rem n d == 0 | |
fb x = if (divides 15 x) then "Fizzbuzz" else if (divides 3 x) then "Fizz" else if (divides 5 x) then "Buzz" else show x | |
fizzbuzz :: [Int] -> [String] | |
fizzbuzz xs = [fb x | x <- xs] |
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
import System.Environment | |
import Control.Exception | |
import System.IO.Error | |
main = runFizzBuzz `catch` handler | |
runFizzBuzz :: IO() | |
runFizzBuzz = do (countTo:_) <- getArgs | |
let numbers = map fizzbuzz [0..(read countTo)] | |
mapM_ putStr $ map (\n -> n ++ ", ") $ init numbers | |
putStrLn $ last numbers | |
divides d n = rem n d == 0 | |
fizzbuzz n | mDividesN 15 = "fizzbuzz" | |
| mDividesN 3 = "fizz" | |
| mDividesN 5 = "buzz" | |
| otherwise = show n | |
where mDividesN m = m `divides` n | |
handler :: IOError -> IO() | |
handler e | |
| isUserError e = ioError $ userError "An integer argument must be supplied" | |
| otherwise = ioError e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment