Lecture 4, June 26
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.
Code
The first half of lecture was spent talking about recursion with the factorial function as an example. We spent substantial time discussing how the function is evaluated and how type checking happens.
The second half was spent on structures.
#lang typed/racket (require typed/test-engine/racket-tests) (require "../include/uchicago151.rkt") (: factorial (Nonnegative-Integer -> Positive-Integer)) ; Computes n! (define (factorial n) (cond [(= n 0) 1] [else (* n (factorial (- n 1)))])) (check-expect (factorial 0) 1) (check-expect (factorial 3) 6) (check-expect (factorial 5) 120) (check-expect (factorial 8) 40320) ; Untyped racket stuructures are defined like this: ;(define-struct Cylinder (r h)) (define-struct Cylinder ([r : Real] [h : Real])) (define cyl1 (make-Cylinder 3 4)) (: Cyl-Vol (Cylinder -> Real)) ; Cyl-Vol computes the volume of a cylinder: pi * r^2 * h (define (Cyl-Vol cyl) (* pi (sqr (Cylinder-r cyl)) (Cylinder-h cyl))) (: Cyl-Double (Cylinder -> Cylinder)) ; Doubles the size of a given cylinder ; Example: (Cyl-Double (make-Cylinder 2 5)) ;; -> (make-Cylinder 4 10) (define (Cyl-Double c) (make-Cylinder (* 2 (Cylinder-r c)) (* 2 (Cylinder-h c)))) (define-struct Vec ([x : Real] [y : Real] [z : Real])) (: mag (Vec -> Real)) (define (mag v) (sqrt (+ (sqr (Vec-x v)) (sqr (Vec-y v)) (sqr (Vec-z v))))) (check-expect (mag (make-Vec 3 4 0)) 5) (: negate (Vec -> Vec)) (define (negate v) (make-Vec (- (Vec-x v)) (- (Vec-y v)) (- (Vec-z v)))) (check-expect (negate (make-Vec 3 2 -4)) (make-Vec -3 -2 4)) (: vec-add (Vec Vec -> Vec)) (define (vec-add u v) (make-Vec (+ (Vec-x u) (Vec-x v)) (+ (Vec-y u) (Vec-y v)) (+ (Vec-z u) (Vec-z v)))) (: vec-dot (Vec Vec -> Real)) (define (vec-dot u v) (+ (* (Vec-x u) (Vec-x v)) (* (Vec-y u) (Vec-y v)) (* (Vec-z u) (Vec-z v)))) (test)