3
\$\begingroup\$

I would like to reverse a list using cdr, car and cons. Since lists in lisp are asymmetrical (can only insert at the beginning), I am interested on how one would write a procedure to do that without using (append). Please review my code.

(define (reverse l)
    (define (aux orig result)
        (if (null? orig) result
                (aux (cdr orig) (cons (car orig) result))))
    (aux l '()))

Is this good enough? Are there better or more efficient ways to do this?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Given that you don't want to use append, this looks great to me. I'm not sure if I can even think of a different way to do it.

My only suggestion would be naming related. l is a terrible name for a variable - it's too close to 1. orig is questionable, since it's not really the original list, it's the list you're currently "popping" (logically, not literally) off of - so you could simply rename both l and orig to something like lst or xs or elems or ....

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.