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
No comments:
Post a Comment