Skip to content

Instantly share code, notes, and snippets.

@xenophobia
Created December 17, 2013 14:41
Show Gist options
  • Select an option

  • Save xenophobia/8005907 to your computer and use it in GitHub Desktop.

Select an option

Save xenophobia/8005907 to your computer and use it in GitHub Desktop.
import Control.Monad.Writer
import Control.Monad.Reader
type FizzBuzz = ReaderT Int (Writer String) ()
tellFizz :: FizzBuzz
tellFizz = do
n <- ask
when (n `rem` 3 == 0) $ tell "Fizz"
tellBuzz :: FizzBuzz
tellBuzz = do
n <- ask
when (n `rem` 5 == 0) $ tell "Buzz"
tellNumber :: FizzBuzz
tellNumber = do
n <- ask
when (n `rem` 3 /= 0 && n `rem` 5 /= 0) $ tell (show n)
fizzbuzz :: FizzBuzz
fizzbuzz = do
tellFizz
tellBuzz
tellNumber
runFizzBuzz :: Int -> String
runFizzBuzz = execWriter . runReaderT fizzbuzz
main :: IO ()
main = mapM_ putStrLn $ map runFizzBuzz [1..30]
{-
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment