schemeplai

how to write scheme function that takes two lists and return one list like this


how to implement this function

if get two list (a b c), (d e)

and return list (a+d b+d c+d a+e b+e c+e)

list element is all integer and result list's element order is free

I tried this like

(define (addlist L1 L2)
  (define l1 (length L1))
  (define l2 (length L2))
  (let ((result '()))
     (for ((i (in-range l1)))
        (for ((j (in-range l2)))
           (append result (list (+ (list-ref L1 i) (list-ref L2 j))))))))

but it return error because result is '()

I don't know how to solve this problem please help me


Solution

  • It doesn't work because functions like append don't mutate the containers. You could fix your problem with a mutating function like append!. Usually functions that mutate have a ! in their name like set! etc.

    But it's possible to achieve that without doing mutation. You'd have to change your algorithm to send the result to your next iteration. Like this:

    (let loop ((result '()))
       (loop (append result '(1)))
    

    As you can see, when loop will get called, result will be:

    '()
    '(1)
    '(1 1)
    '(1 1 1)
    ....
    

    Following this logic you should be able to change your algorithm to use this method instead of for loop. You'll have to pass some more parameters to know when you have to exit and return result.

    I'll try to add a more complete answer later today.

    Here's an implementation of append! I just wrote:

    (define (append! lst1 lst2)
      (if (null? (cdr lst1))
        (set-cdr! lst1 lst2)
        (append! (cdr lst1) lst2)))