Created
August 3, 2011 13:39
-
-
Save ajalab/1122655 to your computer and use it in GitHub Desktop.
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
| 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 |
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
| 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 |
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.
Author
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
fizzbuzz3.hs (based on fizzbuzz1.hs):