How to recursively reverse a list using only basic operations?

前端 未结 3 1128
予麋鹿
予麋鹿 2020-11-29 12:38

I was wondering how to reverse a list using only basic operations such as cons, first, rest, empty?, etc.

No helper functions or accumulators allowed, and the funct

3条回答
  •  一生所求
    2020-11-29 13:18

    (define (reverse x)
      (let loop ((x x) (y '()))
        (if (null? x)
            y
            (let ((temp (cdr x)))
              (set-cdr! x y)
              (loop temp x))))))
    

    Really one of the few ways to do it efficiently. But still sort of a helper procedure.

    Other way, but not tail-recursive, and if the append doesn't use a set-cdr! it's really unusable for large lists.

    (define (reverse L)
      (if (null? l)
          '()
           (append (reverse (cdr L)) (list (car L)))))
    

提交回复
热议问题