#lang racket ;; CSE 413 16au ;; Lecture 4 sample code ;; Hal Perkins ;; Scope - many x's (define x 10) (define (add1 x) (+ x 1)) (define (double x) (+ x x)) (define (double-add x) (double (add1 x))) (define (addx n) (+ x n)) ;; Reverse function - several attempts (define lst '(a b c)) ;; first attempt - right recursion, wrong list construction (define (rev1 lst) (if (null? lst) '() (cons (rev1 (cdr lst)) (car lst)))) ;; second attempt - doesn't work (wrong 2nd argument to append) (define (rev2 lst) (if (null? lst) '() (append (rev2 (cdr lst)) (car lst)))) ;; third attempt - ok (define (rev3 lst) (if (null? lst) '() (append (rev3 (cdr lst)) (list (car lst))))) ;; local bindings ;; double reverse - evaluates reverse twice (define (revrev lst) (append (reverse lst) (reverse lst))) ;; double reverse - evaluate reverse once and create local binding (define (revrev2 lst) (let ([r (reverse lst)]) (append r r))) ;; let semantics - all expressions evaluated in surrounding scope (define (f1) (let ([x 1] [y 2]) (+ x y))) (define (f2) (let ([x 1] [y (+ x 1)]) (+ x y))) ;; let* - each binding added before next expression evaluated (define (f3) (let* ([x 1] [y (+ x 1)]) (+ x y))) (define (f4) (let* ([y (+ x 1)] [x 1]) (+ x y)))