Skip to content

Instantly share code, notes, and snippets.

@jjant
Created November 11, 2018 00:45
Show Gist options
  • Select an option

  • Save jjant/6f0ac64ec8a634c8a5998d4e8260bf95 to your computer and use it in GitHub Desktop.

Select an option

Save jjant/6f0ac64ec8a634c8a5998d4e8260bf95 to your computer and use it in GitHub Desktop.
module FizzBuzz where
import Data.Foldable (traverse_)
divisibleBy :: Int -> Int -> Bool
divisibleBy divisor x = x `mod` divisor == 0
data FizzResult v pt pf rt rf
= Val v pf rf
| Fizz pt rf
| Buzz pf rt
| FizzBuzz pt rt
deriving (Show)
mkFizzBuzz :: (v -> Either pf pt) -> (v -> Either rf rt) -> v -> FizzResult v pt pf rt rf
mkFizzBuzz p1 p2 v =
case (p1 v, p2 v) of
(Right pt, Right rt) -> FizzBuzz pt rt
(Right pt, Left rf) -> Fizz pt rf
(Left pf, Right rt) -> Buzz pf rt
(Left pf, Left rf) -> Val v pf rf
boolToEither :: Bool -> Either () ()
boolToEither True = Right ()
boolToEither False = Left ()
type FizzBuzz = FizzResult Int () () () ()
fizzbuzz :: Int -> FizzBuzz
fizzbuzz =
let divisibleBy' d x = boolToEither (divisibleBy d x)
in mkFizzBuzz (divisibleBy' 3) (divisibleBy' 5)
main :: IO ()
main = traverse_ (print . fizzbuzz) [1 .. 100]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment