person2000
person2000

Reputation: 11

Haskell: Sum of last 2 integers in a string

I am new to Haskell and I'm attempting a task in which the result should be the sum of the last two integers in a string.

I completely understand the overall addition part however it is the manipulation of the string recursively that I'm struggling with. To attempt the task I first 'flipped' the string with the last integer becoming the first for said string to be split after the nth term, in this case 2.

For example, with the given string 1,2,3,4,5,6,7. The result would be 13 as in 6+7=13.

sum' :: [a] -> [a]
sum' = foldl (\acc x -> x : acc) []

sum' :: [a] -> [a]
sum' [] = []
sum' xs = let h = splitAt 1 xs in h

sum' :: (Num a) => [a] -> a 
sum' [] = 0 
sum' (xs:x) = xs + sum' (x)

main :: IO()
main = do
          print(sum'[1,2,3,4,5,6,7])

It is currently very messy and extremely inefficient (not to mention broken). Any help on the functions of haskell which will help me is greatly appreciated.

Upvotes: 1

Views: 217

Answers (2)

John F. Miller
John F. Miller

Reputation: 27217

Working with the ends of lists is hard. My suggestion would be to reverse the list and take 2 elements off the front.

let a:b:_ = reverse [1,2,3,4,5,6,7] in a + b

By the way what you have here is not a String but a List of Int. While Strings are always lists in Haskell, not all Lists are Strings

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476537

You should recurse until only two elements are left in the list. So you implement two clauses for the normal behavior, and like some extra ones for the "corner cases".

The base case (1) is a list of two elements in which you need to sum up the elements; the recursive case (2) deals with a list with three or more elements, and recurses on the tail of the list:

sumlast2 :: Num a => [a] -> a
sumlast2 [x1, x2] = …         -- (1)
sumlast2 (_:xs@(_:_:_)) = …   -- (2)
-- … extra clauses for corner cases …

where you still need to fill in the parts. In the second clause (2), xs is thus tail of the list: a list with all elements except the first one. You thus will need to define sumlast2 with three or more elements in terms of sumlast2.

Upvotes: 0

Related Questions