From a3861fd23f352231765c512ebcd6c108114e3ade Mon Sep 17 00:00:00 2001 From: rbasso Date: Wed, 13 Jul 2016 01:04:18 +0900 Subject: [PATCH] grains: Change return type to Maybe Change the return type of function `square` from an `Integer` to a `Maybe Integer`. Add three test: - `square (-1)` - `square 0 ` - `square 65 ` Add a stub solution. --- exercises/grains/Grains.hs | 5 +++++ exercises/grains/example.hs | 11 ++++++++--- exercises/grains/grains_test.hs | 23 ++++++++++++++++------- 3 files changed, 29 insertions(+), 10 deletions(-) create mode 100644 exercises/grains/Grains.hs diff --git a/exercises/grains/Grains.hs b/exercises/grains/Grains.hs new file mode 100644 index 000000000..7f79c2282 --- /dev/null +++ b/exercises/grains/Grains.hs @@ -0,0 +1,5 @@ +module Grains (square, total) where + +square = undefined + +total = undefined diff --git a/exercises/grains/example.hs b/exercises/grains/example.hs index e1e491edb..ec7028cf1 100644 --- a/exercises/grains/example.hs +++ b/exercises/grains/example.hs @@ -1,7 +1,12 @@ module Grains (square, total) where -square :: Int -> Integer -square = (2 ^) . pred +import Data.Maybe (fromJust) + +square :: Integer -> Maybe Integer +square x + | x < 1 = Nothing + | x > 64 = Nothing + | otherwise = Just . (2^) . pred $ x total :: Integer -total = pred $ 2 ^ (64 :: Int) +total = sum . map (fromJust . square) $ [1..64] diff --git a/exercises/grains/grains_test.hs b/exercises/grains/grains_test.hs index afe15f861..683d3be34 100644 --- a/exercises/grains/grains_test.hs +++ b/exercises/grains/grains_test.hs @@ -19,22 +19,31 @@ main = exitProperly $ runTestTT $ TestList i :: Integral a => a -> Integer i = fromIntegral +mi :: Integral a => Maybe a -> Maybe Integer +mi = fmap fromIntegral + grainsTests :: [Test] grainsTests = [ testCase "square 1" $ - 1 @=? i (square 1) + Just 1 @=? mi (square 1) , testCase "square 2" $ - 2 @=? i (square 2) + Just 2 @=? mi (square 2) , testCase "square 3" $ - 4 @=? i (square 3) + Just 4 @=? mi (square 3) , testCase "square 4" $ - 8 @=? i (square 4) + Just 8 @=? mi (square 4) , testCase "square 16" $ - 32768 @=? i (square 16) + Just 32768 @=? mi (square 16) , testCase "square 32" $ - 2147483648 @=? i (square 32) + Just 2147483648 @=? mi (square 32) , testCase "square 64" $ - 9223372036854775808 @=? i (square 64) + Just 9223372036854775808 @=? mi (square 64) + , testCase "square negative" $ + Nothing @=? mi (square (-1)) + , testCase "square 0" $ + Nothing @=? mi (square 0) + , testCase "square bigger than 64" $ + Nothing @=? mi (square 65) , testCase "total grains" $ 18446744073709551615 @=? i total ]