Last active
August 29, 2015 14:13
-
-
Save callerobertsson/ebf9a0ba6c58d77157dc to your computer and use it in GitHub Desktop.
Haskell: Calculates number of cans in a pyramid or sum of all cans in pyramids
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
-- cans.hs | |
-- Calculate number of cans in one pyramid | |
cansInPyramid :: Int -> Int | |
cansInPyramid 1 = 1 | |
cansInPyramid n = n + cansInPyramid (n - 1) | |
-- Smaller solution | |
cansInPyramid' n = sum [1..n] | |
-- Calculates number of cans in all pyramids | |
sumOfPyramids :: Int -> Int | |
sumOfPyramids 1 = 1 | |
sumOfPyramids n = cansInPyramid n + sumOfPyramids (n - 1) | |
-- Smaller solution | |
sumOfPyramids' n = sum $ map cansInPyramid' [1..n] | |
main = do | |
print $ cansInPyramid 8 -- 36 | |
print $ sumOfPyramids 8 -- 120 | |
print $ cansInPyramid' 8 -- 36 | |
print $ sumOfPyramids' 8 -- 120 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment