Created
September 11, 2017 20:36
-
-
Save sbuller/656955d9eea315cf63089728e0877281 to your computer and use it in GitHub Desktop.
An implementation of FizzBuzz inspired by a Tom Scott video
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
-- borrowed from FSharp | |
(|>) :: t -> (t -> t1) -> t1 | |
a |> b = b a | |
-- The game rules: | |
fizzbuzz :: Integer -> String | |
fizzbuzz n = let | |
-- We can create rules that process numbers. | |
-- The incoming numbers are paired with an accumulated String | |
rule :: Integer -> String -> (Integer, Maybe String) -> (Integer, Maybe String) | |
rule num word (i, acc) | (i `mod` num) /= 0 = (i, acc) | |
| acc == Nothing = (i, Just word) | |
| otherwise = (i, fmap (++ word) acc) | |
-- The final step always produces a string, either from the accumulator or the index | |
showNumberOtherwise :: (Integer, Maybe String) -> String | |
showNumberOtherwise (_, Just word) = word | |
showNumberOtherwise (i, _) = show i | |
in | |
(n, Nothing) |> rule 3 "Fizz" |> rule 5 "Buzz" |> showNumberOtherwise | |
-- Process the numbers from 1..100 and print the results | |
main :: IO () | |
main = mapM_ putStrLn $ map fizzbuzz [1..100] | |
-- vim: et |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment