Skip to content

Instantly share code, notes, and snippets.

@johntyree
Created April 4, 2013 19:49
Show Gist options
  • Save johntyree/5313582 to your computer and use it in GitHub Desktop.
Save johntyree/5313582 to your computer and use it in GitHub Desktop.
Haskell
-- A nice collection of FizzBuzz implementations
-- GistID: 5313582
module Main where
import Data.List
fb :: (Show a, Integral a) => a -> String
fb i
| i `rem` 15 == 0 = "FizzBuzz"
| i `rem` 5 == 0 = "Buzz"
| i `rem` 3 == 0 = "Fizz"
| otherwise = show i
fb2 :: (Show a, Integral a) => a -> String
fb2 i = let buzz = if i `rem` 5 == 0 then "Buzz" else ""
fizz = if i `rem` 3 == 0 then "Fizz" else ""
num = if null (fizz ++ buzz) then show i else ""
in fizz ++ buzz ++ num
fb3 :: (Show a, Integral a) => ([String], a, a) -> a -> ([String], a, a)
fb3 (s, 3, 5) _ = ("FizzBuzz":s, 1, 1)
fb3 (s, 3, five) _ = ("Fizz":s, 1, five+1)
fb3 (s, three, 5) _ = ("Buzz":s, three+1, 1)
fb3 (s, three, five) i = (show i:s, three+1, five+1)
fb4 :: (Show a, Integral a) => a -> String
fb4 i | null desc = show i
| otherwise = desc
where
desc = concat [ label | (j, label) <- tags, i `rem` j == 0]
tags = sort [(3, "Fizz"), (5, "Buzz")]
main1 = mapM_ (putStrLn . fb) [1..20]
main2 = mapM_ (putStrLn . fb2) [1..20]
main3 = let fst3 (a,_,_) = a in mapM_ putStrLn . reverse . fst3 $ foldl fb3 ([],1,1) [1..20]
main4 = mapM_ (putStrLn . fb4) [1..20]
main = main1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment