;; 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-reader.ss" "lang")((modname week5_w_full) (read-case-sensitive #t) (teachpacks ((lib "image.ss" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.ss" "teachpack" "2htdp"))))) ; new syntax: ; (local [defn1 .... defnN] exp) ; defn can be function def, variable def, or define-struct ; these defns are *only* visible inside the local ;recall sorting: (define (sorta l) (local [(define (sort l) (cond [(empty? l) l] [else (insert (first l) (sort (rest l)))])) (define (insert x l) (cond [(empty? l) (list x)] [else (cond [(< x (first l)) (cons x l)] [else (cons (first l) (insert x (rest l)))])])) ] (sort l))) (define x 1) (+ (local [(define x 2) (define y (+ x 2))] (+ y 2)) 1) ; sixteenth power (define (sixteenth i) (local [(define double (* i i)) (define quad (* double double)) (define eth (* quad quad))] (* eth eth))) ;vs.: ;(define (sixteenth i) ; (* i i i i... ;biggest : list-of-numbers -> number ;returns largest number in the list of positive numbers, returns 0 if empty (define (biggest l) (cond [(empty? l) 0] [else (cond [(< (first l) (biggest (rest l))) (biggest (rest l))] [else (first l)])])) (check-expect (biggest (list 1 2 3 4)) 4) (check-expect (biggest (list 5 3 1)) 5) (time (biggest (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))) (time (biggest (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))) (time (biggest (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17))) ; yikes! ; time(0) = 3 ; time(n+1) = time(n) + time(n) ; = 2 * time(n) ; time(n) = 3*2^n ; n = 100 roughly larger # of steps than # of atoms in known universe (define (fast-biggest l) (cond [(empty? l) 0] [else (local [(define bigrest (fast-biggest (rest l)))] (cond [(< (first l) bigrest) bigrest] [else (first l)]))])) (time (fast-biggest (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15))) (time (fast-biggest (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))) (time (fast-biggest (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17)))