Scheme append procedure

20,876

Well by switching the two lists around like that (switching the position of m and l when calling append recursively), you'll get the first item of the first list followed by the first item of the second list etc.

If you don't want that, you should keep l as the first argument and m as the second. So you get:

(define (append l m)
 (if (null? l) '()
  (cons (car l) (append (cdr l) m))))

Of course this doesn't work as wanted either, because now you only get the first list back and nothing is appended at all. What you need to do is, once the first list is fully appended (i.e. once l is empty), you need to return the second one as the tail, like this:

(define (append l m)
 (if (null? l) m
  (cons (car l) (append (cdr l) m))))
Share:
20,876

Related videos on Youtube

Chris McKnight
Author by

Chris McKnight

Updated on February 18, 2020

Comments

  • Chris McKnight
    Chris McKnight about 4 years

    I'm having trouble appending a list to another list. Below is my code. When I run (append '(1 2) '(3 4)) I get '(1 3 2 4).

    I want the output to be '(1 2 3 4)

    (define (append l m)
     (if (null? l) '()
      (cons (car l) (append m (cdr l)))))
    

    Thanks

Related