listhaskellfunctional-programmingtuplesfold

Haskell foldr1 lambda function which adds tuple values


I have been scratching my head trying to figure this out. How do I use foldr1 (or any other fold for that matter) in order to get the sum of tuples in a list.

Example:

list = [(1,2), (3,4)]
sum = 10

I've tried foldr1 (\x y -> fst(x) + snd(x) + y) [(1,2),(3,4)] but it doesn't work and I suspect that it has to do with the the types being created while executing the fold not being tuples.

When I run the command described above I get this:

foldr1 (\x y -> fst(x) + snd(x) + y) [(1,2),(3,4)]

• Occurs check: cannot construct the infinite type: a ~ (a, a)
    • In the second argument of ‘(+)’, namely ‘y’
      In the expression: fst (x) + snd (x) + y
      In the first argument of ‘foldr1’, namely
        ‘(\ x y -> fst (x) + snd (x) + y)’
    • Relevant bindings include
        y :: (a, a) (bound at <interactive>:30:12)
        x :: (a, a) (bound at <interactive>:30:10)
        it :: (a, a) (bound at <interactive>:30:1)

What am I doing wrong? Is the fold function not meant for this (I've solved this using sum and map together and it got the right answer)?


Solution

  • foldr1 :: (a -> a -> a) -> [a] -> a is meant for when the result of the fold is the same type as the elements of the list. Since your result is a number and the list elements are tuples it isn't the right function here. foldr is probably the correct one:

    foldr (\x y -> fst(x) + snd(x) + y) 0 [(1,2),(3,4)]