reverse list - scheme

前端 未结 8 1925
清酒与你
清酒与你 2020-12-11 05:46

I\'m trying to reverse a list, here\'s my code:

(define (reverse list)
  (if (null? list) 
     list
      (list (reverse (cdr list)) (car list))))
         


        
8条回答
  •  既然无缘
    2020-12-11 06:18

    Tail recursive approach using a named let:

    (define (reverse lst)
      (let loop ([lst lst] [lst-reversed '()])
        (if (empty? lst)
            lst-reversed
            (loop (rest lst) (cons (first lst) lst-reversed)))))
    

    This is basically the same approach as having a helper function with an accumulator argument as in Oscar's answer, where the loop binding after let makes the let into an inner function you can call.

提交回复
热议问题