Skip to content

Instantly share code, notes, and snippets.

@callerobertsson
Last active August 29, 2015 14:13
Show Gist options
  • Save callerobertsson/ebf9a0ba6c58d77157dc to your computer and use it in GitHub Desktop.
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
-- 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