Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active December 25, 2015 20:49
Show Gist options
  • Save davidallsopp/7a724fa54e21f6a6a45b to your computer and use it in GitHub Desktop.
Save davidallsopp/7a724fa54e21f6a6a45b to your computer and use it in GitHub Desktop.
Fizzbuzz one-liners in Haskell, following on from jbrains and srbaker (https://gist.github.com/jbrains/2a29465457bddcca0c45)
-- Using pattern match - adapted from http://rosettacode.org/wiki/FizzBuzz#Scala
-- (Naturally, this can be formatted sensibly rather than as a gratuitous one-liner!)
fizzbuzz :: Integer -> String
fizzbuzz n=case map(mod n)[3,5]of[0,0]->"FizzBuzz";[0,_]->"Fizz";[_,0]->"Buzz";_->show n
-- The canonical version at http://rosettacode.org/wiki/FizzBuzz#Haskell using guards
-- can be packed into an even shorter one-liner:
fizzbuzz :: Integer -> String
fizzbuzz x|mod x 15==0="FizzBuzz"|mod x 3==0="Fizz"|mod x 5==0="Buzz"|otherwise=show x
-- And even shorter by using True instead of otherwise
fizzbuzz x|mod x 15==0="FizzBuzz"|mod x 3==0="Fizz"|mod x 5==0="Buzz"|True=show x
-- But these all need a wrapper to print the outputs from 1-100!
@davidallsopp
Copy link
Author

Note that otherwise is actually defined as True in the Prelude - see https://hackage.haskell.org/package/base-4.8.1.0/docs/Prelude.html

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