Search code examples
listlambdaschemefold

foldr - adding zipped elements of two lists


I have a hard time to figure out the functionality of foldr. I'm doing homework and we are supposed to build a fuction (no need of foldr), that zips the elements of two lists (f.e. '(1 2 3) (4 5 6) -> (1 4) (2 5) (3 6).

That worked pretty okay so far:

(define (zip list1 list2)
  (cond
    [(or (empty? list1) (empty? list2)) '()]
      [else (cons (list (car list1) (car list2)) (zip (cdr list1) (cdr list2)))]))

But now I have to build a function, which uses the zip function I made before and combines two lists with a function f and return them as a list. (fe. (zipfunction + '( 1 2) '(3 4) -> (4 6)

I got the basic idea of foldr it will recursively apply a function I supply to a list from right to left, but I cant get behind it how to do so with several lists and several functions and if I need an accumulator variable or not.

Can someone help me with that?

Thank you in advance!


Solution

  • A more natural answer would be to use map:

    (map + '(1 2) '(3 4))
    

    Of course, a map can be expressed using foldr:

    (foldr (lambda (x y acc)
             (cons (+ x y) acc))
           '()
           '(1 2)
           '(3 4))
    

    What you should remember when using foldr is that it consumes one or more lists as input and each one of its elements is passed as a parameter to a procedure, and in that procedure the accumulated result is also passed as a parameter with the specified initial value (an empty list in this case); it's up to you to decide how to combine / accumulate the parameters in the procedure to yield a result.