Saturday, 4 June 2016

Haskell: Calculate sum of all elements in a list


listUtil.hs
sumOfElements :: [Integer] -> Integer
sumOfElements [] = 0
sumOfElements (x:xs) = x + sumOfElements(xs)

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> sumOfElements []
0
*Main> 
*Main> sumOfElements [2, 3, 5, 7]
17
*Main> 
*Main> sumOfElements [2]
2
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment