A common and simple way of appending two lists is as follows:
(define (append a b)
(if (null? a)
b
(cons (car a) (append (cdr a) b))))
Why does this work? When we reach the final element of a
, my clearly incorrect belief is that we will be calling (cons [the original list a, built out of many calls to (cons (car a) ...)] [the original list b])
. In short, I can't see why function does not return (cons a b)
, which would be a cons
cell containing two lists. Even if I'm wrong about the a
part, why is it valid to add b
to our output as a whole list, without first breaking it down in to its individual elements?
I suspect that a worked example will be of great value to an answer.