Created
February 23, 2022 08:58
-
-
Save nobsun/13a23d31d7c2a6758feb64fcb123f21a to your computer and use it in GitHub Desktop.
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 GHC2021 #-} | |
module Main where | |
import Data.Char ( isDigit ) | |
import Data.Maybe ( mapMaybe ) | |
main :: IO () | |
main = interact (drive repl) | |
drive :: ([String] -> [String]) -> (String -> String) | |
drive f = unlines . f . lines | |
repl :: [String] -> [String] | |
repl ins = mapMaybe output $ eval $ initState ins | |
data MState = MState { inputs :: [String], output :: Maybe String } | |
initState :: [String] -> MState | |
initState ins = MState { inputs = ins, output = Nothing } | |
eval :: MState -> [MState] | |
eval state = state : rests | |
where | |
rests | isFinal state = [] | |
| otherwise = eval (step state) | |
isFinal :: MState -> Bool | |
isFinal state = case inputs state of | |
"bye":_ -> True | |
_ -> False | |
step :: MState -> MState | |
step state = case inputs state of | |
l:ls -> if all isDigit l | |
then state { inputs = ls, output = Just (fizzbuzz (read l)) } | |
else state { inputs = ls, output = Nothing } | |
fizzbuzz :: Int -> String | |
fizzbuzz n | |
| n `mod` 15 == 0 = "FizzBuzz" | |
| n `mod` 5 == 0 = "Buzz" | |
| n `mod` 3 == 0 = "Fizz" | |
| otherwise = show n | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment