;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname reverse-list) (read-case-sensitive #t) (teachpacks ((lib "docs.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "docs.rkt" "teachpack" "htdp")) #f))) ; function 1 for reversing a list (define (reverse-list-1 lst) (if (null? lst) ; if the list is empty lst ; return the empty list ; otherwise, append the reverse of the rest of the list with the first element ;(as a list) (append (reverse-list-1 (cdr lst)) (list (car lst))) ) ) ;(reverse-list-1 '(1 2 3 4 (5 6 (7 8)) 9 10 (11 12))) ; function 2 for reversing a list (define (reverse-list-2 lst) (reverse-aux lst '())) ; call an auxiliary function (define (reverse-aux lst acc) (if (null? lst) ; if the list is empty acc ; return the accumulator (reverse-aux (cdr lst) ; advance the recursion over the list (cons (car lst) acc)))) ; cons current element with accumulator ;(reverse-list-2 '(1 2 3 4 (5 6 (7 8)) 9 10 (11 12))) ;(reverse-list-2 '(1 2 3 4)) ;a higher-order function to reverse a list -- better then function 2 (define (foldll g ys u) (if (null? ys) u (foldll g (cdr ys) (g u (car ys))))) (define (reverse-list-3 lst) (foldll (lambda (x y) (cons y x)) lst '())) ;(reverse-list-3 '(1 2 3))