CS 135 Midterm 2
CS 135 Midterm 2. Outline of The Session. Structures Lists Association Lists Recursions Types of Recursions. Structures. Structures. Allow you to store several values in one entity e.g. posn – predefined structure in Scheme (define- struct posn (x y)) The following are created:
CS 135 Midterm 2
E N D
Presentation Transcript
Outline of The Session • Structures • Lists • Association Lists • Recursions • Types of Recursions
Structures • Allow you to store several values in one entity • e.g. posn – predefined structure in Scheme • (define-structposn (x y)) • The following are created: • Constructor: (make-posn x y) • Selectors: (posn-x) (posn-y) • Predicate: posn? • (make-posn 3 2) is in its most simplified form
Structures • Example: • (define-struct chair (color material)) • (define mychair (make-chair ‘blue ‘wood)) • (chair-color mychair) => ‘blue • (chair-material mychair) => ‘wood • Predicate: chair?
Structures: Design Recipe • Define the structure • Write the data definition • What are the types of each field? • Create a template for a function that consumes the structure
Structures: Design Recipe (define-struct student (first last id)) ;; a Student = (make-student String String Number) ;; my-student-fn: Student -> Any (define (my-student-fn data) … (student-first data) … … (student-last data) … … (student-id data) …)
Structures: Examples Question 1: (define-struct student (first last id)) ;; a Student = (make-student String String Number) • Write a function “swap” that takes a Student as input, and outputs another Student with the first name and last name swapped.
Structures: Examples Question 2 • Define a struct called “fivenum” that has five fields, all of which are numbers. • Write a function “fivenum-avg” that takes a fivenum as input, and output a number that is the average of the five fields that are in fivenum.
Structures: Examples HTDP, Section 7, Question 2: Develop data and structure definition for a collection of 3D shapes. The collection includes: • Cubes, with relevant properties being the length of an edge • Prisms, which are rectangular solids and with relevant properties being length, width, and height • Spheres, with relevant property being the radius Develop the function “volume”. The function consumes a 3D shape and produces the volume of the object. • The volume of a cube is the cube of the length of one its edges. • The volume of a prism is the product of its length, width, and height. • The Volume of a sphere is 4/3 * PI * r^3
Lists • Lists vs. Structs • Unbounded vs. fixed amount of data • An ordered set of data elements, each containing a list to its successor
Lists • List selector functions: • First • Cons • Rest • Built-in predicates: • Empty? • Cons? • Member? • Other list functions: • Length • Reverse
Lists ;; A List is one of: ;; * empty ;; * (cons Any List) • empty is also a list When stepping through code, a list, like structures, cannot be simplified any further.
Lists • (define lst (cons 2 (cons 3 (cons 4 empty)))) • Selectors: • (first lst) => 2 • (rest lst) => (cons 3 (cons 4 empty)) • (first (rest lst)) => 3
Lists: Box-and-Pointer Diagrams • Write out the code for these Box-and-Pointer diagrams
Lists: Box-and-Pointer Diagrams • Solutions • (cons (cons empty empty) (cons 3 empty)) • (cons (cons 1 empty) (cons (cons 4 (cons 7 (cons 8 empty))) (cons (cons empty empty) empty)))
Lists: Box-and-Pointer Diagrams • Draw Box-and-Pointer diagrams: • (cons 1 (cons 2 (cons 3 empty))) • (cons (cons 1 (cons 2 empty)) (cons (cons 3 (cons 4 empty)) empty)) • (cons (cons (cons 3 empty) (cons 4 (cons 6 empty))) (cons 7 (cons (cons 8 empty) empty)))
Coding with Lists ;; my-list-fn: (listof Any) -> Any (define (my-lst-fnlst) (cond [(empty? lst) …] [else … (first lst) … (my-lst-fn (rest lst)) … ])) This is for a general list function
Coding with Lists Question 1: Write a function “addone” that takes a (listofNum) as input, and output a (listofNum) with each element of list incremented by 1.
Lists: Tracing (define (addonelon) (cond [(empty? lon) empty] [else (cons (add1 (first lon) ) (addone(rest lon)))])) • (addone(cons 3 (cons 1 (cons 9 (cons 4 empty))))) • (cons 4 (addone(cons 1 (cons 9 (cons 4 empty))))) • (cons 4 (cons 2 (addone(cons 9 (cons 4 empty))))) • (cons 4 (cons 2 (cons 10 (addone(cons 4 empty))))) • (cons 2 (cons 4 (cons 6 (cons 5 (addone empty))))) • (cons 2 (cons 4 (cons 6 (cons 5 empty))))
Coding with Lists Question 2: Develop the function “string-append-n”, which consumes a list of strings and produces a single string resulting from appending all the strings together. Use the built-in function “string-append”: String String -> String, which appends two strings. If the list is empty, produce an empty string “”.
List Abbreviations • (cons 1 (cons 2 (cons 3 empty))) • (list 1 2 3) • (cons ‘Apple (cons ‘Orange (cons ‘Fruit empty))) • ‘(Apple Orange Fruit)
Association Lists • List of pairs • Pair is a two-element list • First element is the key • Second element is the value • E.g. Storing definitions
Association Lists (define (my-al-fnalst) (cond [(empty? alst) ...] [else … (first (first alst) ;; first key … (second (first alst)) ;; first value … (my-al-fn (rest alst))]))
Association Lists: Example Question 1: Create the function “remove-entry” for an association list. The function “remove-entry” consumes an association list and a key, and produces the association list without the key/value pair for the given key. If the key is not in the association list, return the original association list.
Recursion • You have just used recursion on lists • A function that calls itself in order to compute data of unknown size • Must have a base case
Recursion • Natural number recursion • Used to work with any natural number N • Base case is usually N = 0 Question: Write a function “fac” that takes a natural number as input, and outputs the factorial of that number. (fac 4) -> 4*3*2*1 -> 24
Recursion Question 1: Develop list-pick0 that takes a (listof Any) and a natural number as input, and produces the n-th element of the list (index starts at 0). (You can assume n < length of list) (list-pick0 (list ‘hello ‘world) 0) -> ‘hello
Structural Recursion • Each recursive call leaves all parameters unchanged or moves the recursion one step closer to a base case • e.g. traversing a list until empty
Accumulative Recursion • Parameter(s) contain partial answers (define (my-reverse lst0) ;; wrapper function (my-rev-helper lst0 empty)) (define (my-rev-helper lstacc) ;; helper function (cond [(empty? lst) acc] [else (my-rev-helper (rest lst) (cons (first lst) acc))]))
Generative Recursion • Parameters are freely calculated at each step (define (euclid-gcd n m) (cond [(zero? m) n] [else (euclid-gcd m (remainder n m))])
Practice Problems Determine whether the following recursive functions uses structural recursion, accumulative recursion, or generative recursion.
Type of Recr: Practice Problems n is a natural number (define (facn) (cond [(zero? n) 1] [else (* n (fac (sub1 n)))]))
Type of Recr: Practice Problems (define (fac n) (fac-helper n 1)) (define (fac-helper n acc) (cond [(zero? n) acc] [else (fac-helper (sub1 n) (* n acc))]))
Type of Recr: Practice Problems n is a natural number (define (collatz n) (cond [(= n 1) empty] [(even? n) (cons (/ n 2) (collatz (/ n 2)) [(odd? n) (cons (add1 (* n 3)) (collatz (add1 (* n 3))))]))
Type of Recr: Practice Problems Lon is a list of numbers (define (sum lon) (cond [(empty? lon) 0] [else (+ (first lon) (sum (rest lon)))]))
Any Final Questions?Good luck on your midterm!khzhu@uwaterloo.ca