Weekend Coding Kata Challenge – Fizzbuzz TDD Using Haskell

I wanted to check out different stacks recently. The goal is to pick an interesting new language and go deep on some aspects of it – understanding how to implement a simple web server with or without the language-specific framework. The main thing is to implement everything in TDD.

I had a brief look at Haskell in mid last year. It was really weird and mind-blowing when I first got to know Haskell. I had always planned to revisit the language, so I did it. Here is my Fizzbuzz kata implementation using the Haskell stack.

https://github.com/suryast/fizzbuzz-hs

module FizzBuzzSpec (spec) where

import Test.Hspec
import FizzBuzz

spec :: Spec
spec =
  describe "fizzBuzz" $ do

    it "should print fizz if divisable by 3" $
       -- | Given
       let input = 3
           expected = "fizz"

       -- | When
           actual = fizzBuzz input

       -- | Then
       in actual `shouldBe` expected

    it "should print the input if not divisable by 3 or 5" $
       -- | Given
       let input = 4
           expected = "4"

       -- | When
           actual = fizzBuzz input

       -- | Then
       in actual `shouldBe` expected
    
    it "should print buzz if not divisable by 5" $
       -- | Given
       let input = 5
           expected = "buzz"

       -- | When
           actual = fizzBuzz input

       -- | Then
       in actual `shouldBe` expected

    it "should print fizzbuzz if not divisable by 15" $
       -- | Given
       let input = 15
           expected = "fizzbuzz"

       -- | When
           actual = fizzBuzz input

       -- | Then
       in actual `shouldBe` expected
module FizzBuzz where

fizzBuzz :: Int -> [Char]
fizzBuzz input = if fizz(input) ++ buzz(input) == ""
    then show input
    else fizz(input) ++ buzz(input)

fizz :: Int -> [Char]
fizz input = if mod input 3 == 0 then "fizz" else ""

buzz :: Int -> [Char]
buzz input = if mod input 5 == 0 then "buzz" else ""

Setting up the Haskell’s Stack/Cabal stack was quite time-consuming, and it took the most time. Learning about the syntax and how to write tests using Hspec was quite exciting otherwise. I am quite keen to learn more about Haskell in the future.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.