Using the built-in map and zip functions, define a Scheme function zipadd that takes two lists of numbers and returns the a list consisting of the corresponding elements added together. You may assume that the lists are the same length. For example (zipadd ‘(1 2 3) ‘(4 5 6)) is (5 7 9). (A correct solution not using zip and map will be worth 8 points.)
I am not sure how to do this. I would really like to know the solution before my exam tomorrow. Can anyone help me please?
For starters, Racket doesn’t come with a
zipprocedure, although it’s trivial to implement one:Now regarding your question – a solution using only
mapis the simplest way to solve this problem and it’s very similar to the above procedure, just think what could be used to fill the blank:Although it’s a bit more contrived, you can use
zipto reach the same solution (and get full marks). Try to figure out how it works –zipsticks together all pairs of elements in both lists, creating a list of two-element lists. Afterwards,mapwill traverse that list and apply a procedure to each element (remember: each element is a list of two elements), creating a new list with the results:Finally and for completeness’ sake, a solution without using
maporzip. It’s an implementation ofmapfor the special case where the numbers on both lists must be added pair-wise:(*) Remember: both lists are assumed to have the same length.
Try to write all the variations of the solution, it’ll be interesting to compare different approaches to solve the same problem. And if you have to use
mapandzipto get full marks then by all means use the second version above, just be aware that’s not the simplest nor the most efficient way to express the solution to the problem at hand.