Home > Back-end >  Mapping over two lists with uneven lengths - Scheme
Mapping over two lists with uneven lengths - Scheme

Time:09-21

I am implementing a procedure 'map2' that takes in two lists and returns the sum of each element. If the lists are uneven, only the sums of the shortest list is returned. My code is:

(define (map2 proc items1 items2)
  (if (null? items1)
    '()
    (cons (proc (car items1) (car items2))
          (map2 proc (cdr items1) (cdr items2)))))

Example of use should be:

(maps2 '(1 2 3 4) '(3 4 5)) --> (4 6 8)

My question is how do implement the part that handles uneven lists?

CodePudding user response:

Your solution is almost correct - you just have to check both lists and stop, when one of them is empty.

(define (map2 proc items1 items2)
  (if (or (null? items1) (null? items2))
    '()
    (cons (proc (car items1) (car items2))
          (map2 proc (cdr items1) (cdr items2)))))

Example:

> (map2   '(1 2 3 4) '(3 4 5))
'(4 6 8)
> (map2 * '(1 2) '(3 4 5))
'(3 8)
  • Related