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?

asked Dec 29, 2015 at 16:30
\$\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 ....

answered Dec 29, 2015 at 17:16
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.