Skip to content

Instantly share code, notes, and snippets.

@singpolyma
Created April 8, 2015 18:43
Show Gist options
  • Save singpolyma/45fc9ec3509110fd3add to your computer and use it in GitHub Desktop.
Save singpolyma/45fc9ec3509110fd3add to your computer and use it in GitHub Desktop.

Revisions

  1. singpolyma created this gist Apr 8, 2015.
    13 changes: 13 additions & 0 deletions TDD.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    module TDD (add) where

    import qualified Data.Text as T

    data ArgumentError = ArgumentError deriving (Show)

    add :: String -> Integer
    add s = sum $ map toI $ T.split (\d -> d == ',' || d == '\n') (T.pack s)

    toI :: T.Text -> Integer
    toI s = case reads (T.unpack s) of
    ((n, _) : _) -> n
    _ -> 0
    57 changes: 57 additions & 0 deletions Test.hs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    module Main (main) where

    import Control.Applicative
    import Test.Framework (defaultMain, testGroup, Test)
    import Test.Framework.Providers.HUnit
    import Test.Framework.Providers.QuickCheck2
    import Test.QuickCheck
    -- import Test.QuickCheck.Instances ()
    import Test.HUnit hiding (Test)
    import Data.List (intercalate)

    import qualified TDD

    testDecode1 :: Assertion
    testDecode1 = assertEqual "for 1" 1 (TDD.add "1")

    propIntegerDecodeLoop :: Integer -> Bool
    propIntegerDecodeLoop num = TDD.add (show num) == num

    testDecodeEmpty :: Assertion
    testDecodeEmpty = assertEqual "for empty" 0 (TDD.add "")

    propTwoShouldDecode :: Integer -> Integer -> Bool
    propTwoShouldDecode x y = TDD.add (show x ++ "," ++ show y) == x + y

    propSomeShouldDecode :: [Integer] -> Bool
    propSomeShouldDecode xs = TDD.add (intercalate "," (map show xs)) == sum xs

    newtype Delimiter = Delimiter String deriving (Show)

    instance Arbitrary Delimiter where
    arbitrary = Delimiter <$> elements [",", "\n"]

    propSomeShouldDecodeDelim :: [Integer] -> Delimiter -> Bool
    propSomeShouldDecodeDelim xs (Delimiter d) = TDD.add (intercalate d (map show xs)) == sum xs

    tests :: [Test]
    tests =
    [
    testGroup "One number" [
    testCase "\"1\" returns 1" testDecode1,
    testProperty "Integer should decode" propIntegerDecodeLoop
    ],
    testGroup "No number" [
    testCase "\"\" returns 0" testDecodeEmpty
    ],
    testGroup "Two numbers" [
    testProperty "Two numbers should sum" propTwoShouldDecode
    ],
    testGroup "Some numbers" [
    testProperty "Some numbers should sum" propSomeShouldDecode,
    testProperty "Some numbers should sum with comma or newline" propSomeShouldDecodeDelim
    ]
    ]

    main :: IO ()
    main = defaultMain tests