Created
October 25, 2012 15:42
-
-
Save bil-bas/3953481 to your computer and use it in GitHub Desktop.
FizzBuzz in Haskell
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
-- Write a program that prints the numbers from 1 to 100. | |
-- But for multiples of three print “Fizz” instead of the number and for the multiples | |
-- of five print “Buzz”. For numbers which are multiples of both three and five | |
-- print “FizzBuzz”." | |
-- Generate the Output for a single index. | |
fizzBuzzN :: Int -> String | |
fizzBuzzN x | |
| and $ map multipleOf [3, 5] = "FizzBuzz" | |
| multipleOf 3 = "Fizz" | |
| multipleOf 5 = "Buzz" | |
| otherwise = show x | |
where multipleOf y = x `mod` y == 0 | |
-- Output FizzBuzz values for numbers in range. | |
fizzBuzz :: [Int] -> IO () | |
fizzBuzz a = mapM_ putStrLn $ map fizzBuzzN a | |
-- Output FizzBuzz values for the numbers from 1 to 100. | |
fizzBuzz100 = fizzBuzz [1..100] |
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
# And, for comparison, implementations in Ruby as close as possible to | |
# my Haskell version. | |
def fizz_buzz_n(x) | |
multiple_of = ->(y) { x % y == 0 } | |
case | |
when [3, 5].all?(&multiple_of) then "FizzBuzz" | |
when multiple_of.(3) then "Fizz" | |
when multiple_of.(5) then "Buzz" | |
else x.to_s | |
end | |
end | |
def fizz_buzz(a); a.each {|x| puts fizz_buzz_n(x) } end | |
# Can just run the method, since we can have "naked expressions" in Ruby scripts. | |
fizz_buzz 1..100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting spin on the Ruby case expression (Not better, but, erm, different):