;; LISTS uber Alles ;; ---------------- ;; +-----------------------------------------+ ;; | | ;; V | ;; A LOS (List of Strings) is one of: | ;; -- empty | ;; -- (cons String LOS) x----------------------- ;; another cycle!!!! ;; let's make examples: empty (cons "hello" empty) (cons "world" (cons "hello" empty)) ;; .... ;; Is this one: (cons "hello" (cons "world" empty)) ;; show how to use a data definition to check ;; whether some value "belongs" ;;; Recursion! Well-founded ordering. Tarski's fixed-point ;;; theorem. Halting problem. Fundamental limits on knowledge. ;;; Godel's incompleteness theorem. Cool math. ;;; What can you infer from this? ;;; A New Structure: ;;; constructor: cons ;;; -- creates a 2-slot structure called 'first' and 'rest' slot ;;; accessor: first, rest ;;; -- extract the first and the rest slot ;;; predicate: cons? ;;; -- is the given 'thing' (value) a cons structure ;;; A New Unique Value: ;;; empty -- it's a constant, just like 5 or true ;;; empty? -- it's different from every other value in the world ;;; CONS is original constructor. Lists ubiquitous! ;;; History of LISP. ;;; Make students define (on paper) template for LOS. ;;; Then make them write COUNT. ;;; Then do it, with recipe: contract, purpose, examples, test. ;; LOS -> Number ;; count the number of strings in the given LOS #; (define (count l) (cond [(empty? l) ...] [(cons? l) ... (first l) ... (count (rest l)) ...])) ;; finish: examples etc. (define (count l) (cond [(empty? l) 0] [(cons? l) (+ 1 (count (rest l)))])) (count (list "1" "2" "3")) ;; size : LOS -> Number ;; count the number of chars in the given LOS (define (size l) (cond [(empty? l) 0] [(cons? l) (+ (string-length (first l)) (size (rest l)))])) (size (list "1" "2" "3")) ;; in? : LOS String -> Boolean ;; is s on the given list? (define (in? l s) (cond [(empty? l) false] [(cons? l) (or (string=? (first l) s) (in? (rest l) s))])) (in? (list "1" "2" "3") "2") ;; skip how-often if you are short of time! replace and the last ;; example are far more important! ;; how-often : LOS String -> Number ;; how often is s on the given list? (define (how-often l s) (cond [(empty? l) 0] [(cons? l) (cond [(string=? (first l) s) (+ 1 (how-often (rest l) s))] [else (how-often (rest l) s)])])) (how-often (list "1" "2" "3") "2") ;; replace : LOS String String -> LOS ;; replace new with old on l (define (replace l old new) (cond [(empty? l) empty] [(cons? l) (cond [(string=? (first l) old) (cons new (replace (rest l) old new))] [else (cons (first l) (replace (rest l) old new))])])) (replace (list "1" "2" "3") "2" "x") ;; +-----------------------------------------+ ;; | | ;; V | ;; A LOC (List of Customers) is one of: | ;; -- empty | ;; -- (cons Customer LOS) x---------------------- ;; Customer is: (make-customer Title String String) ;; Title is one of: 'Mr. or 'Mrs. (define-struct customer (title first last)) ;; make examples (cons (make-customer 'Mr. "Olin" "Shivers") empty)