I\'m trying to reverse a list, here\'s my code:
(define (reverse list)
(if (null? list)
list
(list (reverse (cdr list)) (car list))))
>
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.