Skip to content

Instantly share code, notes, and snippets.

@merijn
Last active January 24, 2019 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merijn/cd0e7918a96fe913cf7d66833e8da354 to your computer and use it in GitHub Desktop.
Save merijn/cd0e7918a96fe913cf7d66833e8da354 to your computer and use it in GitHub Desktop.
Generalised FizzBuzz
{-# 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