Lecture 6, June 30
The lecture notes I post serve two purposes: to remind you of the topics we discussed and to provide any interesting code examples I did during lecture. I would describe these notes as an outline, not a summary, of what I talked about during lecture. You are not expected to be able to learn the material simply from examining these notes, nor is reading these notes a reasonable substitute for attending lecture.
Local
We started by discussing local definitions. There are two primary reasons to use local definitions: style and efficiency. In general, local definitions should be used to reduce (or eliminate) duplicated code. This reduces the typing you have to do, saving you time. It also reduces the work another person would have to do to understand your code. In some cases it can substantially reduce the amount of computations that are done in the evaluation of your code, which can make your program much faster.
(: f (Number -> Number)) (define (f x) (+ x 5)) (f 6) (local {(: x Number) (define x 6)} (+ x 5)) (define-struct Cube ([s : Real])) (: Cube-volume (Cube -> Real)) (define (Cube-volume c) (* (Cube-s c) (Cube-s c) (Cube-s c))) (: Cube-volume2 (Cube -> Real)) (define (Cube-volume2 c) (local {(: r Real) (define r (Cube-s c))} (* r r r))) (: fib (Integer -> Integer)) (define (fib n) (cond [(<= n 1) 1] [else (+ (fib (- n 1)) (fib (- n 2)))])) ; slow-example computes (fib n)^3 (: slow-example : Integer -> Integer) (define (slow-example n) (* (fib n) (fib n) (fib n))) (: fast-example : Integer -> Integer) (define (fast-example n) (local {(: fib-n Integer) (define fib-n (fib n))} (* fib-n fib-n fib-n))) (time (slow-example 25)) (time (fast-example 25)) (: cube : Integer -> Integer) (define (cube n) (* n n n)) (: fast-example2 : Integer -> Integer) (define (fast-example2 n) (cube (fib n)))
Lists
We began discussing lists. It is extremely important to be familiar with the following five built in values and functions:
- empty : Null
- cons : (All (A) (A (Listof A) -> (Listof A)))
- first : (All (A) ((Listof A) -> A))
- rest : (All (A) ((Listof A) -> (Listof A)))
- empty? : Any -> Boolean
(: l (Listof Integer)) (define l (cons 2 (cons 3 (cons 5 (cons 7 empty))))) ; list-len computes the length of a list (: list-len ((Listof Any) -> Integer)) (define (list-len l) (cond [(empty? l) 0] [else (+ 1 (list-len (rest l)))])) ; list-sum computes the sum of numbers in a list (: list-sum ((Listof Number) -> Number)) (define (list-sum l) (cond [(empty? l) 0] [else (+ (first l) (list-sum (rest l)))])) ;(check-expect (list-sum (cons 1 (cons 4 (cons 3 empty)))) 8) ;(check-expect (list-sum '(1 4 3)) 8) ; list-nth Returns the nth item in a list ; We begin indexing with number 1 ; (list-nth l 1) is the same is (first l) (: list-nth (All (A) ((Listof A) Integer -> A))) (define (list-nth l i) (cond [(empty? l) (error "Item not found")] [(<= i 1) (first l)] [else (list-nth (rest l) (- i 1))]))