Created
February 22, 2012 03:38
-
-
Save chrisyco/1881130 to your computer and use it in GitHub Desktop.
FizzBuzz variations
This file contains 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: an example program, similar in purpose to the infamous | |
-- Hello World, that serves to demonstrate the features and syntax of | |
-- the language in which it is written. | |
-- | |
-- The rules of the game are as follows: | |
-- | |
-- 1. If the number is divisible by 3, return \"Fizz\"; | |
-- | |
-- 2. If the number is divisible by 5, return \"Buzz\"; | |
-- | |
-- 3. If the number is divisible by both 3 and 5, return \"FizzBuzz\"; | |
-- | |
-- 4. Otherwise, simply return the number. | |
module FizzBuzz where | |
import Control.Applicative | |
import Control.Monad | |
import Data.List | |
main = mainBasic -- Change this to use another implementation | |
-- Utility functions | |
numbers = [1..100] :: [Int] | |
runWith = mapM_ putStrLn . flip map numbers | |
-- Basic version | |
mainBasic = runWith runBasic | |
runBasic n | |
| n `mod` 15 == 0 = "FizzBuzz" | |
| n `mod` 3 == 0 = "Fizz" | |
| n `mod` 5 == 0 = "Buzz" | |
| otherwise = show n | |
-- Using 'guard' | |
mainGuard = runWith runGuard | |
runGuard n = | |
case fizz ++ buzz of | |
[] -> show n | |
word -> word | |
where | |
fizz = guard (n `mod` 3 == 0) >> "Fizz" | |
buzz = guard (n `mod` 5 == 0) >> "Buzz" | |
-- Roll a wheel with spikes at different positions | |
-- See <http://www.reddit.com/r/programming/comments/10d7w/fizzbuzz_spoilers/c10g19> | |
mainWheel = mapM_ putStrLn $ zipWith ($) wheel [1..100] | |
where | |
wheel = cycle [o, o, f, o, b, f, o, o, f, b, o, f, o, o, (++) <$> f <*> b] | |
o = show | |
f = const "Fizz" | |
b = const "Buzz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment