Skip to content

Instantly share code, notes, and snippets.

@corajr
Created February 5, 2016 19:25
Show Gist options
  • Save corajr/095d0b05cf8a448c5ffe to your computer and use it in GitHub Desktop.
Save corajr/095d0b05cf8a448c5ffe to your computer and use it in GitHub Desktop.
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
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