how can I add for example [1,2,3] to [5,4,6] to return [6,6,8] This is what I have so far:
func1 :: [Int]->[Int]->[Int]
func1 x y = [a+b|a<-x,b<-y]
Should I try and remove the elements that I don't want or is there a simpler way to do this?
You're looking for zipWith
. In particular func1 x y = zipWith (+) x y
. You can "eta reduce" to remove those extra parameters as well: func1 = zipWith (+)
. This is the most efficient form I can think of.
Your current method doesn't work because [a+b | a <- x, b <- y]
forms two nested loops, one over the x
es and one inside it over the y
s. This is the nature of list comprehensions and it's based on Set Builder Notation. One way to read it is "for each a from x, for each b from y, give me (a + b)
" while we actually want to run through x
and y
together.
The simple answer is zipWith:
zipWith (+) [1,2,3][5,4,6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With