Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created July 14, 2016 17:44
Show Gist options
  • Save adomokos/aa5d97cbfb3a5d17982c1786d5c8e584 to your computer and use it in GitHub Desktop.
Save adomokos/aa5d97cbfb3a5d17982c1786d5c8e584 to your computer and use it in GitHub Desktop.
String Calculator in Haskell
module StringCalculator where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
import Data.List.Split (splitOn)
calculator' :: String -> Char -> Integer
calculator' x c = sum $ coerceString x c
calculator :: String -> Integer
calculator x = sum $ coerceString x ','
coerceString :: String -> Char -> [Integer]
coerceString x c = map (coerce) (splitOn [c] x)
where
coerce "" = 0
coerce a = read a :: Integer
main :: IO ()
main = hspec $ do
describe "String Calculator" $ do
it "returns 0 for empty string" $ do
calculator "" `shouldBe` 0
it "returns 1 for '1'" $ do
calculator "1" `shouldBe` 1
it "returns 2 for '2'" $ do
calculator "2" `shouldBe` 2
it "returns 3 for '1,2'" $ do
calculator "1,2" `shouldBe` 3
it "returns 6 for '1,2,3'" $ do
calculator "1,2,3" `shouldBe` 6
it "can accept a separator" $ do
calculator' "1;2;3" ';' `shouldBe` 6
it "can accept a separator" $ do
calculator' "1ن2ن3" 'ن' `shouldBe` 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment