Created
February 5, 2016 19:25
-
-
Save corajr/095d0b05cf8a448c5ffe to your computer and use it in GitHub Desktop.
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
module ClosestToZero where | |
closestToZero :: [Int] -> Maybe Int | |
closestToZero [] = Nothing | |
closestToZero xs = Just $ foldl1 f xs | |
where f x y = case compare (abs x) (abs y) of | |
LT -> x | |
EQ -> abs x | |
GT -> y |
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
module ClosestToZeroSpec where | |
import Test.Hspec | |
import Test.QuickCheck | |
import ClosestToZero | |
main :: IO () | |
main = hspec spec | |
spec :: Spec | |
spec = | |
describe "closestToZero" $ do | |
describe "when passed an empty list" $ | |
it "should return Nothing" $ | |
closestToZero [] `shouldBe` Nothing | |
describe "when passed a list of one element" $ | |
it "should return Just [that element]" $ property $ | |
\i -> closestToZero [i] == Just i | |
describe "when passed a list of one element and its negation" $ | |
it "should return Just [the positive element]" $ property $ | |
\i -> closestToZero [i, -i] == Just (abs i) | |
describe "when passed any list" $ | |
it "should return the same value backwards and forwards" $ property $ | |
\xs -> closestToZero xs == closestToZero (reverse xs) | |
describe "when passed some specified lists" $ | |
it "should return the expected results" $ do | |
closestToZero [1,2,5,-2] `shouldBe` Just 1 | |
closestToZero [ -8, 3, 11, 2, 1, 4, 21, -3, -2 ] `shouldBe` Just 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment