Skip to content

Instantly share code, notes, and snippets.

@bradparker
Last active May 25, 2018 04:28
Show Gist options
  • Save bradparker/6a12dfebf308719c875c to your computer and use it in GitHub Desktop.
Save bradparker/6a12dfebf308719c875c to your computer and use it in GitHub Desktop.
Haskell Buzz
module Main where
import Control.Applicative
import Data.Monoid
fizz n
| n `mod` 3 == 0 = Just "Fizz"
| otherwise = Nothing
buzz n
| n `mod` 5 == 0 = Just "Buzz"
| otherwise = Nothing
fizzBuzz n = maybe (show n) id (f <> b <|> f <|> b)
where
f = fizz n
b = buzz n
main = putStr $ unlines $ map fizzBuzz [1..100]
fizzBuzz :: Int -> IO ()
fizzBuzz 0 = putStrLn ""
fizzBuzz n =
putStr $ unlines $ map fizzBuzzCollect [1..n]
where
fizzBuzzCollect n
| multOf 3 n && multOf 5 n = "FizzBuzz"
| multOf 3 n = "Fizz"
| multOf 5 n = "Buzz"
| otherwise = show n
where
multOf n = (== 0) . flip mod n
module Main (main) where
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Control.Monad (guard)
multipleOf :: Int -> Int -> Bool
multipleOf a b = a `mod` b == 0
fizz :: Int -> Maybe String
fizz n = "Fizz" <$ guard (n `multipleOf` 3)
buzz :: Int -> Maybe String
buzz n = "Buzz" <$ guard (n `multipleOf` 5)
fizzBuzz :: Int -> String
fizzBuzz n = fromMaybe (show n) (fizz n <> buzz n)
-- Infinite fizz buzz, what you always wanted
main :: IO ()
main = putStrLn (unlines (map fizzBuzz [1..]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment