Created
March 8, 2018 13:13
-
-
Save moreau-nicolas/cc0d2d8a2d32b62308ecdbd343e01824 to your computer and use it in GitHub Desktop.
Haskell FizzBuzz
This file contains hidden or 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
module FizzBuzz (main, fizzBuzz) where | |
import Data.Foldable | |
import Data.Maybe | |
isMultipleOf :: Int -> Int -> Bool | |
n `isMultipleOf` f = n `mod` f == 0 | |
fizzBuzz :: Int -> String | |
fizzBuzz x = fromMaybe (show x) (fold rules x) | |
where | |
rules = [ | |
(`isMultipleOf` 3) ~> "Fizz", | |
(`isMultipleOf` 5) ~> "Buzz" | |
] | |
rule ~> result = \n -> if rule n then Just result else Nothing | |
main :: IO () | |
main = mapM_ putStrLn $ map fizzBuzz [1..100] |
This file contains hidden or 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
module FizzBuzzSpec (main) where | |
import FizzBuzz (fizzBuzz) | |
import Test.Hspec | |
main :: IO () | |
main = hspec $ do | |
describe "FizzBuzz" $ do | |
it "should return \"1\" when given 1" $ do | |
fizzBuzz 1 `shouldBe` "1" | |
it "should return \"2\" when given 2" $ do | |
fizzBuzz 2 `shouldBe` "2" | |
it "should return \"4\" when given 4" $ do | |
fizzBuzz 4 `shouldBe` "4" | |
it "should return \"Fizz\" when given 3" $ do | |
fizzBuzz 3 `shouldBe` "Fizz" | |
it "should return \"Fizz\" when given 6" $ do | |
fizzBuzz 6 `shouldBe` "Fizz" | |
it "should return \"Fizz\" when given 9" $ do | |
fizzBuzz 9 `shouldBe` "Fizz" | |
it "should return \"Buzz\" when given 5" $ do | |
fizzBuzz 5 `shouldBe` "Buzz" | |
it "should return \"Buzz\" when given 10" $ do | |
fizzBuzz 10 `shouldBe` "Buzz" | |
it "should return \"Buzz\" when given 20" $ do | |
fizzBuzz 20 `shouldBe` "Buzz" | |
it "should return \"FizzBuzz\" when given 15" $ do | |
fizzBuzz 15 `shouldBe` "FizzBuzz" | |
it "should return`\"FizzBuzz\" when given 30" $ do | |
fizzBuzz 30 `shouldBe` "FizzBuzz" | |
it "should return`\"FizzBuzz\" when given 45" $ do | |
fizzBuzz 45 `shouldBe` "FizzBuzz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment