Skip to content

Instantly share code, notes, and snippets.

@deque-blog
Last active December 17, 2016 17:24
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 deque-blog/3e8ebe35f0ec15178a39c9c9b25616b3 to your computer and use it in GitHub Desktop.
Save deque-blog/3e8ebe35f0ec15178a39c9c9b25616b3 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid((<>))
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Builder as B
-- The API of the fizz buzz
type Rule = B.Builder -> Int -> B.Builder
fizzBuzz' :: [Rule] -> Int -> B.Builder
fizzBuzz' rules i = foldl (\out rule -> out <> rule out i) "" rules
-- Helper function to build the rules
defaultRule :: Rule
defaultRule s n
| s == mempty = B.fromLazyText $ T.pack (show n)
| otherwise = ""
makeRule :: Int -> T.Text -> Rule
makeRule d out _ n
| mod n d == 0 = B.fromLazyText out
| otherwise = ""
-- Usage
testFizzBuzz :: IO ()
testFizzBuzz = do
let fizzBuzz = fizzBuzz' [makeRule 3 "fizz", makeRule 5 "buzz", defaultRule]
print $ map fizzBuzz [3, 5, 7, 15]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment