;; my-reverse : [Listof X] -> [Listof X] ;; reverse the order of the list (define (my-reverse.slow lox) (cond [(empty? lox) empty] [(cons? lox) (append (my-reverse.slow (rest lox)) (list (first lox)))])) ;; reverse-onto : [Listof X] [Listof X] -> [Listof X] ;; reverse lox and append it to the front of ans (define (reverse-onto lox ans) (cond [(empty? lox) ans] [(cons? lox) (reverse-onto (rest lox) (cons (first lox) ans))])) (check-expect (reverse-onto '() '()) '()) (check-expect (reverse-onto '() '(x y z)) '(x y z)) (check-expect (reverse-onto '(a b c) '()) '(c b a)) (check-expect (reverse-onto '(a b c) '(x y z)) '(c b a x y z)) (define (my-reverse lox) (reverse-onto lox '())) (check-expect (my-reverse '()) '()) (check-expect (my-reverse '(1 2 3)) '(3 2 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; fact : Natural -> Natural ;; compute factorial of n (i.e., n * (n-1)* ... * 1) #;(define (fact n) (cond [(zero? n) 1] [else (* n (fact (sub1 n)))])) ;;-------------------------- ;; Accumulator-based design: ;; fact : Natural -> Natural ;; compute factorial of n (i.e., n * (n-1)* ... * 1) (define (fact n) (local (;; Natural Natural -> Natural ;; compute n! * acc (define (fact-accum n acc) (cond [(zero? n) acc] [else (fact-accum (sub1 n) (* n acc))]))) (fact-accum n 1))) (check-expect (fact 0) 1) (check-expect (fact 5) 120)