;; 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-lambda-reader.ss" "lang")((modname week7_f_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"))))) ; Fibonacci sequence: ; f_n = f_n-1 + f_n-2 ; First ten terms: 1 1 2 3 5 8 13 21 34 55 ; lots of fun applications: ; limit of f_n / f_n-1 is known as the "golden ratio" used art and architecture ; Neat! ; fib : number->number ; computes the nth fib. number (define (fib n) (cond [(= n 0) 1] [(= n 1) 1] [else (+ (fib (- n 1)) (fib (- n 2)))])) (check-expect (fib 6) 13) (check-expect (fib 9) 55) ; how many calls do we make to fib? ; f_0 - 1 ; f_1 - 1 ; f_2 - 1 + 2 = 3 ; f_3 - 5 ; f_4 - 9 ; f_5 - 15 ; fib-fast : number->number ; computes the nth fib number quickly, for n>=0 (define (fib-fast n) (cond [(= n 0) 1] [(= n 1) 1] [else (local [(define fnminus2 (fib-fast (- n 2)))] (+ (fib-fast-with-prev (- n 1) fnminus2) fnminus2))])) (check-expect (fib-fast 6) 13) (check-expect (fib-fast 9) 55) ; fib-fast-with-prev : number number -> number ; returns nth fib number given n-1st fib number, for n>=0 (define (fib-fast-with-prev n prev) (cond [(= n 0) 1] [(= n 1) 1] [else (+ prev (fib-fast (- n 2)))])) (check-expect (fib-fast-with-prev 3 2) 3) (check-expect (fib-fast-with-prev 5 5) 8) ; moment for cs #6: The halting problem ; can we write a program that determines whether we have any infinite loops? ; no you provably cannot write such a program ; halts? : (X -> Y) X -> boolean ; returns whether or not a given function runs forever on input X (define (halts? f x) ...) ; diag : (X -> Y) -> boolean (define (diag f) (cond [(halts? f f) (diag f)] [else true])) ; now, what is: (diag diag) ; two possibilities from cond stmt: ; (diag diag) run forever. But that only happens when (halts? diag diag) is true. A contradiction!! ; (diag diag) returns true. But that only happens if *not* (halts? diag diag), a contradiction! ; This isn't just a fact about Racket. It's a fundamental limitation to any (sufficiently powerful) computer