Summing matching pairs from two lists in a tuple - in Haskell
I have a tuple containing two lists of numbers - ([1,2,3,4], [5,6,7,8])
I need to sum the matching pairs of numbers from each list. those. (1 + 5), (2 + 6) etc. List output, i.e. [6,8,10,12]. It should also work for any number of items in lists (2 lists of 5, 2 lists of 6, etc.).
I am trying to use a function using "map sum. Transpose" but cannot get the correct types (as in the tuple). I found a piece of code that works for a list of lists, but don't know how to do the same for tuples of lists (is this possible?). When I try to change types "a" or use Int i compilation for type-mismatch errors.
tupSums :: Num a => [[a]] -> [a] tupSums = map sum . transpose
I'm new to using Haskell, so I don't quite understand the errors I am getting, sorry if the question seems silly.
source to share
It's a good candidate for zipWith
one that takes two lists and concatenates the corresponding items in the list using a specific operator. The following should work:
tupSums :: Num a => ([a],[a]) -> [a] tupSums = uncurry $ zipWith (+)
zipWith (+)
evaluates a function that takes two arguments, each of which are lists, and returns a list of pairwise sums. uncurry
takes a function of two arguments and turns it into a function that takes one tuple. Thus, uncurry $ zipWith (+)
evaluates a function that takes a tuple of lists and returns a list with a pairwise sum.
source to share