Last active
January 24, 2019 08:57
-
-
Save merijn/cd0e7918a96fe913cf7d66833e8da354 to your computer and use it in GitHub Desktop.
Generalised FizzBuzz
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
{-# LANGUAGE ScopedTypeVariables #-} | |
module Main where | |
import Control.Monad (forM_) | |
import Data.Maybe (fromMaybe) | |
generalisedFizzBuzz | |
:: forall a f m | |
. (Foldable f, Semigroup m) | |
=> (a -> m) -> (a -> a -> Bool) -> f (a, m) -> a -> m | |
generalisedFizzBuzz def pred conditions x = fromMaybe (def x) $ evaluate x | |
where | |
evaluate :: a -> Maybe m | |
evaluate = foldMap wrap conditions | |
wrap :: (a, m) -> a -> Maybe m | |
wrap (x, r) y | |
| pred x y = Just r | |
| otherwise = Nothing | |
fizzBuzz :: (Integral n, Show n) => n -> String | |
fizzBuzz = generalisedFizzBuzz show divides [(3, "Fizz"), (5, "Buzz")] | |
where | |
divides :: Integral n => n -> n -> Bool | |
divides x n = n `mod` x == 0 | |
main :: IO () | |
main = forM_ [1..100] $ putStrLn . fizzBuzz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment