0

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?

  • related?: https://stackoverflow.com/questions/19529829/how-to-recursively-reverse-a-list-using-only-basic-operations/19536834#19536834 – Will Ness Jul 04 '16 at 11:26

2 Answers2

1

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)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • This solution is readily acceptable. But my objective is to get the reversed list in l-orig itself. I just want to use l-count as a counter. Any help on this? – The Arcadian Pandit Apr 06 '16 at 16:25
  • Don't. In Scheme, we try to avoid modifying the input, instead we prefer to build a new output, that's the functional programming way. – Óscar López Apr 06 '16 at 17:12
0

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))))
hacoo
  • 121
  • 6