Skip to content

Instantly share code, notes, and snippets.

@ajalab
Created August 3, 2011 13:39
Show Gist options
  • Save ajalab/1122655 to your computer and use it in GitHub Desktop.
Save ajalab/1122655 to your computer and use it in GitHub Desktop.
fizzbuzz :: Int -> String
fizzbuzz n = unlines $ map fizzbuzz' [1 .. n]
where
fizzbuzz' n = let p = n `mod` 3 == 0
q = n `mod` 5 == 0
in case (p, q) of
(p, q) | p && q -> "FizzBuzz"
| p -> "Fizz"
| q -> "Buzz"
| otherwise -> show n
main = putStr $ fizzbuzz 50
fizzbuzz :: Int -> String
fizzbuzz n = unlines $ map fizzbuzz' [1 .. n]
where
fizzbuzz' n = f $ fizz ++ buzz
where
fizz = if n `mod` 3 == 0 then "Fizz" else ""
buzz = if n `mod` 5 == 0 then "Buzz" else ""
f [] = show n
f (x:xs) = (x:xs)
main = (putStr . fizzbuzz) 100
@md2perpe
Copy link

md2perpe commented Aug 3, 2011

fizzbuzz3.hs (based on fizzbuzz1.hs):

fizzbuzz :: Int -> String
fizzbuzz n = unlines $ map fizzbuzz' [1 .. n]
    where
        fizzbuzz' n = case (n `mod` 3, n `mod` 5) of
            (0, 0) -> "FizzBuzz"
            (0, _) -> "Fizz"
            (_, 0) -> "Buzz"
            (_, _) -> show n

main = putStr $ fizzbuzz 50

@md2perpe
Copy link

md2perpe commented Aug 3, 2011

fizzbuzz4.hs:

fizzbuzz :: Int -> String
fizzbuzz n = unlines $ map fizzbuzz' [1 .. n]
    where
        fizzbuzz' n = defaultTo (show n) $ concat $ consIf (n `mod` 3 == 0) "Fizz" $ consIf (n `mod` 5 == 0) "Buzz" $ []

        consIf :: Bool -> a -> [a] -> [a]
        consIf False _ xs = xs
        consIf True  x xs = x : xs

        defaultTo :: [a] -> [a] -> [a]
        defaultTo ys [] = ys
        defaultTo _  xs = xs


main = putStr $ fizzbuzz 50

I think that consIf and defaultTo can be useful in other circumstances.

@ajalab
Copy link
Author

ajalab commented Aug 4, 2011

Thanks for the tip! It became more simple. :)

They were my first Haskell programs..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment