Skip to content

grains: Change return type to Maybe #197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 13, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions exercises/grains/Grains.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module Grains (square, total) where

square = undefined

total = undefined
11 changes: 8 additions & 3 deletions exercises/grains/example.hs
Original file line number Diff line number Diff line change
@@ -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]
23 changes: 16 additions & 7 deletions exercises/grains/grains_test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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
]