Last active
May 25, 2018 04:28
-
-
Save bradparker/6a12dfebf308719c875c to your computer and use it in GitHub Desktop.
Haskell Buzz
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
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] |
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 :: 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 |
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
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