0
votes

I tried reversing a list in scheme using the most basic concept I had about cons,cdr,car. Here,l-orig is the list to be reversed and l-count acts as a counter.

My code goes here:

(define (rev l-orig l-count)
(
    if (null? l-count)
    (cons l-orig '())
    (rev (cons (cdr l-orig) (car l-orig)) (cdr l-count))
)
)
(display (rev '(1 2 3 4 5) '(1 1 1 1 1)))

And the output is (((2 3 4 5) . 1)) Honestly speaking, I am a beginner in lisp and I need a simple help here. If I intend to use this method, can anyone suggest me a correct way of doing it?

2

2 Answers

1
votes

You're attempting to reverse a list using tail recursion, with the help of an accumulator parameter. The best way would be to traverse the original list and cons each of its elements at the head of the accumulator, which will be returned at the end:

(define (rev l-orig l-count)
  (if (null? l-orig)
      l-count
      (rev (cdr l-orig) (cons (car l-orig) l-count))))

Notice that the accumulator starts as an empty list, which is perfect for consing each new element to it:

(rev '(1 2 3 4 5) '())
=> '(5 4 3 2 1)
0
votes

Oscar's answer is right on. You can use a helper function so you don't need to pass in an empty accumulator every time:

(define (rev xs)
  (rev-accum xs '()))

(define (rev-accum xs accum)
  (if (null? xs)
      accum
      (rev-accum (cdr xs) (cons (car xs) accum))))