#lang racket ;; CSE 413 14au ;; Lecture 5 sample code ;; Hal Perkins ;; Local bindings - let and let* (define x 1) (define y 2) (define z 3) (let ((x 10) (y (+ 1 x)) (z (+ y z))) (+ x y z)) (let* ((x 10) (y (+ 1 x)) (z (+ y z))) (+ x y z)) (define foo (lambda (n) (let ((f (lambda (x) (+ 1 x)))) (f n)))) ;; implementing reverse (define nums '(1 -2 413 0 17)) ;; first attempt - doesn't work. Why? (define revmaybe (lambda (lst) (if (null? lst) '() (cons (revmaybe (cdr lst)) (car lst))))) ;; second attempt - works fine, but O(n^2) because ;; append is O(n) (define rev (lambda (lst) (if (null? lst) '() (append (rev (cdr lst)) (list (car lst)))))) ;; different implementation using tail recursion, O(n) ;; (note: tail recursion doesn't always produce speedups or ;; change complexity, but in this case it does so by building ;; up the result one step at a time with a O(1) cons operation) (define revt (lambda (lst) (revaux lst '()))) (define revaux (lambda (rest result) (if (null? rest) result (revaux (cdr rest) (cons (car rest) result))))) ;; fact with simple recursion and tail recursion (define fact (lambda (n) (if (< n 2) 1 (* n (fact (- n 1)))))) (define factt (lambda (n) (factaux n 1))) (define factaux (lambda (n acc) (if (= n 1) acc (factaux (- n 1) (* n acc))))) ;; similar list functions - what's different? (define incrlst (lambda (lst) (if (null? lst) '() (cons (+ 1 (car lst)) (incrlst (cdr lst)))))) (define dbllst (lambda (lst) (if (null? lst) '() (cons (* 2 (car lst)) (dbllst (cdr lst)))))) ;; make the differences into a function parameter and ;; define a higher-order map function (define maplst (lambda (f lst) (if (null? lst) '() (cons (f (car lst)) (maplst f (cdr lst)))))) ;; using maplst with named and anonymous functions (define (incr n) (+ 1 n)) (define (dbl n) (* 2 n)) nums (maplst incr nums) (maplst dbl nums) (maplst (lambda (x) (* 3 x)) nums) (maplst odd? nums) (maplst list nums) (define xvii 17) (maplst (lambda (n) (+ xvii n)) nums)