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 ]