Monday 6 June 2016

Haskell: Calculate sum of numbers in a string

Suppose a string has numbers like “234  54 32 9 123”, Calculate the sum of numbers in the string. For the above input, output should be 234 + 54 + 32 + 9 + 123 = 452.


SumofNumbers.hs
sumOfNumbers :: String -> Integer
sumOfNumbers str = sumOfNumbers' (words str)

sumOfNumbers' :: [String] -> Integer
sumOfNumbers' [] = 0
sumOfNumbers' (x:xs) = (read x :: Integer) + (sumOfNumbers' xs)

getInteger :: String -> Integer
getInteger str = (read str :: Integer)

*Main> :load SumOfNumbers.hs 
[1 of 1] Compiling Main             ( SumOfNumbers.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> sumOfNumbers "234  54 32 9 123"
452
*Main> 
*Main> sumOfNumbers "1 -3 -5 16"
9
*Main> sumOfNumbers ""
0


Previous                                                 Next                                                 Home

No comments:

Post a Comment