Reputation: 1095
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?
Upvotes: 1
Views: 457
Reputation: 236034
For starters, Racket doesn't come with a zip
procedure, although it's trivial to implement one:
(define (zip lst1 lst2)
(map list lst1 lst2))
Now regarding your question - a solution using only map
is 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:
(define (zipadd lst1 lst2)
(map <???> lst1 lst2))
Although it's a bit more contrived, you can use zip
to reach the same solution (and get full marks). Try to figure out how it works - zip
sticks together all pairs of elements in both lists, creating a list of two-element lists. Afterwards, map
will 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:
(define (zipadd lst1 lst2)
(map (lambda (x) <???>) ; x is a list with two numbers, how to add them?
(zip lst1 lst2)))
Finally and for completeness' sake, a solution without using map
or zip
. It's an implementation of map
for the special case where the numbers on both lists must be added pair-wise:
(define (zipadd lst1 lst2)
(if <???> ; if either list is empty (*)
<???> ; then return the empty list
(cons (+ <???> <???>) ; else add the first elements of both lists
(zipadd <???> <???>)))) ; and advance the recursion over both lists
(*) 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 map
and zip
to 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.
Upvotes: 2