Exercise 2.18

Read Exercise 2.18 ~ Solution


Again, two different implementations to help me in thinking about the mechanics of list manipulations.

(define (reverse-ls xs)
  (define (reverse-loop items result)
    (cond ((null? items) result)
          (else (reverse-loop (cdr items) (cons (car items) result)))))
  (reverse-loop xs nil))

(define (reverse-ls xs)
  (append (reverse (cdr xs))
          (list (car xs))))

Update:
As tonghu pointed out in the comments, the 2nd version fails on null input. I was too hasty making two version that I didn’t test them both!

(define (reverse-ls-2 xs)
  (cond ((null? xs) null)
        (else (append (reverse (cdr xs)) 
              (list (car xs))))))

4 thoughts on “Exercise 2.18

  1. Thank you for these awesome solutions. They helped me a lot.

    Is there any online environment for executing Lisp. If not, id there a simple guide for setting up Lisp environment on Mac?

Leave a comment