Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Created October 25, 2012 15:42
Show Gist options
  • Save bil-bas/3953481 to your computer and use it in GitHub Desktop.
Save bil-bas/3953481 to your computer and use it in GitHub Desktop.
FizzBuzz in Haskell
-- 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]
# 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
@bil-bas
Copy link
Author

bil-bas commented Oct 25, 2012

Interesting spin on the Ruby case expression (Not better, but, erm, different):

case [3, 5].select &multiple_of
when [3, 5] then "FizzBuzz"
when [3]     then "Fizz"
when [5]     then "Buzz"
else           x.to_s
end

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