cs 115 – sos review package –...
TRANSCRIPT
CS 115 – SOS Review Package – Midterm Dylan Schnute (Tutor) – [email protected] Erin Vanderstoep (Coordinator) – [email protected] DEFINING FUNCTIONS Similar to mathematics, every definition of a function has three main components:
1. Name of the function 2. Parameters that the function consumes 3. An expression that uses these parameters
General Format: (define (function_name parameter1 parameter2 …)(function_expression)) Ex. (define (f x) (* x x)) (define (g y z)(* (+ y z)(* y y))) BUILT IN FUNCTIONS (- 60 (* 5 5)(/ 45 5)(- 10 2)) ; four basic math functions (+, -‐, /, *) (quotient 70 8) ; gives the integer value when dividing (remainder 70 8) ; gives the remainder when dividing (max 20 25) ; gives the maximum of a group of numbers (min 20 25) ; gives the minimum of a group of numbers (floor 20.8) -‐> 20 (ceiling 20.8) -‐> 21 (sqr 2) -‐> 4 (sqrt 4) -‐> 2 DEFINING CONSTANTS General Format: (define constant_name constant_value) Ex. (define x 4) (define v (* 4 2 x)) ; If we type in v, we would get 32 Rules when defining constants:
1. You cannot define the same variable name twice: (define x 4) (define x 5)
2. Scheme keeps track of variables. Once you define “x”, you can use the definition of x in other functions. (define x 5) (define (y z) (* z y x))
TRACING A step by step simplification of a scheme function by applying substitution rules. Remember to take one step at a time. Example 1:
1. (/ (+ 40 (* (min 5 6 9 3) 2)) 2) -> (/ (+ (* 3 2)) 2) -> (/ (+ 40 6) 2) -> (/ 46 2) -> 23
2. (define (square x y)(+ (* x x) (* y y))) Using the above definition, trace: (square (- 5 2) (* 3 4)) -> (square 3 (* 3 4)) -> (square 3 12) -> (+ (* 3 3) (* 12 12)) ; substitute all parameters into the function at once -> (+ 9 (* 12 12)) -> (+ 9 144) -> 153
THE DESIGN RECIPE The design recipe is a key component of CS 115. Particularly on midterms, the importance of the design recipe can’t be undervalued, and can result in a lot of marks for you. THE CONTRACT A contract is a simple statement of the function name, the types of parameters that it consumes and the type of output. You are telling the user what are the types of things they can input and what types of things they will get out of it. Example If the function squarepower takes in a number and squares it, write: ;; squarepower: num -> num Types of Numbers:
• num: any numeric value • int: for an integer • nat: a natural number (the set of all non-‐negative numbers) • any: any scheme value • (int[>5]): such a format is used for integers with given restrictions
THE PURPOSE A statement that describes the function, its parameters (by name) and what the function should produce. EXAMPLES Provide representations of all the possible cases and outcomes that could arise with the function. BODY The actual code. TESTING (check-‐expect (function_name sample_values) expected_value) If your function output and the expected value are equal, then the test will pass. Scheme will tell you f one or more of your tests have passed or not.
Example 2: Produce a function called sum_square that produces the sum of the squares of any two real numbers, but rounds the number down to the nearest integer. ;;sum_square: num num -> int ;;Purpose: the function consumes two numbers, a and b, produces the sum of the squares of these two numbers, rounded down to the nearest integer. ;;Examples: ;;(sum_square 2 4) -> 20 ;;(sum_square 3.4 6.3) -> 51 ;;(sum_square -5 6) -> 61 (define (sum_square a b) (floor (+ (* a a) (* b b)))) ;;Tests: (check-expect (sum_square 2 4) 20) (check-expect (sum_square 3.4 6.3) 51) (check-expect (sum_square -5 6) 61) STRINGS A value made up of words, letters, numbers, spaces, and punctuation marks that are enclosed in quotation marks (ex. “computer” “computers123” “computer science” “sdalkfjhdf 34 jdhf875”)
“Computer” 0 1 2 3 4 5 6 7
Built-‐In String Functions: (string-‐append “joe” “clark”) -‐> “joe clark” (string-‐length “joe clark”) -‐> 9 (subtring “computer” 0 4) -‐> comp (substring “computer” 0 1) -‐> “c” (subtring “computer” 1) -‐> “omputer” (string>? “nowhere” “here”) -‐> true HELPER FUNCTION A helper function is defined before the main function, and is used to generate similar expressions, express easy/repetitive computations in clear form, and to avoid really long complex definitions.
• You still need the full design recipe for helper functions • Choose meaningful names (not just helper1 etc.)
Example 3 (swap parts): Take a string and swap the front of the string with the back of it. If the string length is odd, make the front part shorter. ;;front_part: string -> string ;;Purpose: To take a string, str, and produce the front part of it ;;Examples: (front_part “computer”) -> “comp” ;;(front_part “compute”) -> “com” (define (front_part str) (substring str (floor (/ (string-length str) 2))))) ;;Tests: (check-expect (front_part “computer”) “comp”) (check-expect (front_part “compute”) “com”) ;;back_part: string -> string ;;Purpose: To take a string, str, and produce the back part of it
;;Examples: (back_part “computer”) -> “uter” ;;(back_part “compute”) -> “pute” (define (front_part str) (substring str (floor (/ (string-length str) 2)))) ;; Tests: (check-expect (front_part “computer”) “uter”) (check-expect (front_part “compute”) “pute”) ;;swap_parts: string -> string ;;Purpose: To take a string, str, and swap the front and back parts ;;Examples: (swap_parts “computer”) -> “utercomp” ;; (swap_parts “compute”) -> “putecom” (define (swap_parts str) (string-append (back_part str) (front_part str))) ;;Tests: (check-expect (swap_parts “computer”) “utercomp”) (check-expect (swap_parts “compute”) “putecom”) BOOLEAN VALUES A Boolean value is either true or false. Boolean functions are functions that produce either true or false. Examples: (= x y) (< x y) (>= x y) Predicates: Ask questions with true or false answers (Ex. zero? number? integer? equal?) We can also build our own predicates: (define (long_name? name) (>= (string-length name) 8)) COMPLEX RELATIONSHIPS AND, OR, NOT
• AND statements mean that both conditions must be true for the entire statement to be true o Ex. (and (= 5 (+ 3 2))(= 1 1)) -> true
• OR statements indicate that only one of the conditions must be true o Ex. (or (= 5 5)(= 1 0)) -> true
• NOT statements require the inner value to be false, for the NOT statement to be true o Ex. (not (= 5 6)) -> true
Example 4 (Complex Relationship Trace): (define str “computer”) (and (<= 6 (string-length str))(equal? “mput” (substring str 2 6)) -> (and (<= 6 (string-length “computer”))(equal? “mput” (substring str 2 6)) -> (and (<= 6 8)(equal? “mput” (substring str 2 6))) -> (and true (equal? “mput” (substring str 2 6))) -> (and (equal? “mput” (substring str 2 6)) -> (and (equal? “mput” (substring “computer” 2 6)) -> (and (equal? “mput” “mput”)) -> (and true) -> (and) -> true
CONDITIONAL RELATIONSHIPS Conditional expressions are basically a series of questions being asked and answers being produced if the answers to the questions are true. They allow you to analyze functions by “cases”. The general form is: (define (function parameter ...) (cond [(question 1) answer 1] [(question 2) answer 2] ... [else answer])) Example 5: Make a function called perfect_relationship, that consumes two strings, representing the names of two people, a positive integer, and a number representing how many hours the two people have been together. If they have known each other for more than 24 hours, they love each other. If they have known each other for less than 24 hours, but the positive integer is even, they still love each other. Otherwise, they hate each other. Make your function produce “name1 loves name2”. ;;perfect_relationship: string string int num[>=0] -> string ;;Purpose: create a string that represents the relationship status between two string, name1 and name2. If atime, is greater than 24, the function produces "name1 loves name2", if its less than or equal to 24, and int is even, then "name1 loves name2". otherwise, we get "name1 hates name2" ;;Examples: (perfect_relationship "miss universe" "Dylan" 5 42) => "miss universe loves Dylan" ;;(perfect_relationship "Dylan" “Scheme" 5 23) => "Dylan hates Scheme" (define (perfect_relationship name1 name2 int atime) (cond [(> atime 24)(string-append name1 " loves " name2)] [(even? int)(string-append name1 " loves " name2)] [else (string-append name1 " hates " name2)])) ;;Tests (check-expect(perfect_relationship "Dylan" "Scheme" 5 23)"Dylan hates Scheme") (check-expect(perfect_relationship "miss universe" "Dylan" 5 42)"miss universe loves Dylan") SYMBOL A symbol starts with the quote ‘ followed by something (ex. ‘blue, ‘red). They are best used for comparisons because it is more efficient than comparing strings. A symbol has a value like the number 6. Type “symbol” in the contract. CHARACTER Ex. #\space, #\1, #\a Built-‐in Predicates:
• char-‐upper-‐case? • char-‐lower-‐case? • char-‐numeric? • char-‐whitespace?
Type “char” in the contract.
INTRO TO STRUCTURES: POSN STRUCTURES A structure is a way of bundling data together to form a single package.
1. You can create functions that consume and/or produce structures 2. Define our own structures 3. Each has
• Constructor function • Selector function • Type Predicate Function
Example 6: A posn is a structure that has two fields containing numbers that represent x and y coordinates. Constructor function: (make-posn num1 num2) Selector functions: (posn-x (make-posn num1 num2)) -> num1 (posn-y (make-posn num1 num2)) -> num2 Type Predicate: (posn? (make-posn num1 num2)) -> true Ex. (define point (make-posn 20 45)) (posn-x point) -> 20 (posn-y point) -> 45 (posn? point) -> true DATA DEFINITIONS AND STRUCTURE DEFINITIONS Data Definition: a comment specifying the types of data being used Ex. ;;a posn is a structure (make-posn xcoord ycoord), where ;;xcoord is a number ;;ycoord is a number Structure Definition: a code defining the structure (like we did above) and allowing us to then use constructor, selector and predicate functions for the definition (define-struct sname (field1 field2 ...)) Doing this gives 3 functions:
1. Constructor: make-sname 2. Selectors: sname-field1, sname-field2 3. Type Predicate: sname?
Example 7: Write a function called reply that consumes an email and a string and produces an email that is a reply to the email consumed using the message given. The contact that sends the reply email will be the same as the contact that received the original email. The contact that receives the reply email will be the same as the contact that sent the original email. The subject of the reply email will be the same as the subject of the original email except that it will start with "RE: ". The message of the reply email will be the string consumed by the reply function, followed by a space, followed by the name of the sender, followed by a space, followed by the word "said" followed by a space followed by the original message. For example:(reply (make-email (make-contact "Sandy Graham" "[email protected]") (make-contact "J.P. Pretti" "[email protected]") "Hello" "I love CS115!") "Me too.") produces(makeemail
(make-contact "J.P. Pretti" "[email protected]") (make-contact "Sandy Graham" "[email protected]") "RE: Hello" "Me too. Sandy Graham said I love CS115!") (define-struct contact (name email_address)) ;; A contact is a structure (make-contact n e) where ;; n is a non-‐empty string representing a person's name and ;; e is a non-‐empty string representing a person's email address (define-struct email (from to subject message)) ;; An email is a structure (make-email f t s m) where ;; f is a contact representing who sent the email, ;; t is a contact representing who received the email, ;; s is a string representing the subject of the email, and ;; m is a non-‐empty string representing the text of the message (define (reply an_email new_message) (make-email (email-to an_email) (email-from an_email) (string-append "RE: " (email-subject an_email)) (string-append new_message " " (contact-name(email-from an_email)) " said " (email-message an_email)))) ;Tests: (check-expect (reply (make-email (make-contact "Sandy Graham" "[email protected]") (make-contact "J.P. Pretti" "[email protected]") "Hello" "I love CS115!") "Me too.")(make-email(make-contact "J.P. Pretti" "[email protected]")(make-contact "Sandy Graham" "[email protected]") "RE: Hello" "Me too. Sandy Graham said I love CS115!")) LISTS Formal Data Definition: A list is either:
• Empty or • (cons f r) where
o f is a value and o r is a list
When we talk about a list, we think of a list with two parts:
1. the FIRST element of the list 2. the REST of the list (which is a list as well)
Ex. (define list1 (cons ‘a (cons ‘b (cons ‘c (cons ‘d empty))))) (define list2 empty) Using the definition of the list above: (first list1) -> ‘a (rest list1) -> (cons ‘b (cons ‘c (cons ‘d empty))) (first (rest alist) -> ‘b (rest (rest alist)) -> (cons ‘c (cons ‘d empty)) (rest (rest (rest (rest list1)))) -> empty
List Template: (define (mylist alist) (cond [(empty? alist) ...] [(cons? alist) ...])) RECURSION The continuous application of a variable that is defined in terms of a past. Recursive Process:
1. Create a base case that ends the program when true 2. Test your base case with given variables 3. Change the variable and recurse the formula
Example 8: Create a function, countdown, that takes in an integer, int, and creates a descending list of numbers, starting with the int, and ending with zero. (define (countdown int) (cond [(zero? int)(cons 0 empty)] [else (cons int (countdown (- int 1)))])) Example 9: Using structural recursion, write a Scheme function called reciprocate that consumes a list and produces a list of numbers and symbols by reciprocating each entry in the list (the reciprocal of x is 1=x). If the input list entry is 0, then its reciprocal is the symbol ’Infinity. Likewise, if the list entry is ’Infinity, then its reciprocal is 0. Finally, if the list entry is not a number or the symbol ’Infinity, then it should be skipped. For example, (reciprocate (cons 2 (cons 0 (cons ’Infinity (cons "boo" empty))))) produces (cons 0.5 (cons ’Infinity (cons 0 empty))). ;; reciprocate: list -‐> list (define (reciprocate alist) (cond [(empty? alist)empty] [(equal? 'Infinity (first alist)))(cons 0 (reciprocate (rest alist)))] [(not (number? (first alist)))(reciprocate (rest alist))]
[(zero? (first alist))(cons 'infinity (reciprocate (rest alist)))] [else (cons (/ 1 (first alist))(reciprocate (rest alist)))]))
(reciprocate empty) -> empty (reciprocate (cons 2 empty)) -> (cons 0.5 empty) (reciprocate (cons 0 (cons 5 (cons 'infinity (cons 2 empty))))) -> (cons ‘infinity (cons 0.2 (cons 0 (cons 0.5 empty)))) (reciprocate (cons 'infinity (cons 0 (cons 5 (cons "computer" empty))))) -> (cons 0 (cons ‘infinity (cons 0.2 empty)))
Practice Questions 1. Assume the following constants have been defined:
(define str “1”) (define a 10) (define b -1) (define mylist (cons ‘x (cons ‘y (cons ‘z empty))))
a. (* (+ 4 1) (- 10 5)) b. (/ ((- 5 1)) (+ 1 1)) c. (or (not (> a b)) (and (> a 3) (> b 10))) d. (integer? “115”) e. (and (integer? str) (> str b)) f. (and (< str b) (integer? str)) g. (first (rest (rest (mylist))) h. (rest (first (mylist))
2. Give a full trace starting with each of the following Scheme expressions: a. (define z 5)
(define (f x y) (* (- x y) 2)) (f a (+ a 1))
b. (cond [(> (posn-x (make-posn 3 5)) 4 (+ 2 2)] [(> 5 4) “a2”] [else ‘a3])
3. Consider the following contract for a function my-fun: my-fun: string[len>0] (union num symbol) -> (listof boolean) Is the contract satisfied for each of the following applications of the function my-fun? Answer Yes or No.
a. (my-fun “hello” ‘hello) b. (my-fun “hello” ‘hello 5) c. (my-fun “” 3.4) d. (my-fun “-123” -123)
Is the contract satisfied for each of the following possible produced values of the function my-‐fun? Answer Yes or No.
e. true f. (cons true (cons 6 empty)) g. empty h. (cons false empty)
4. The function num-vowels consumes a string and produces the number of characters in the string that are values (a, e, i, o, u). If the string does not contain any vowels, then it produces ‘vowel-free. The function header is: (define (num-vowels astring)…)
a. Give a contract of num-‐vowels b. Give a purpose for num-‐vowels c. Give examples for num-‐vowels
5. Recall the structure and data definitions of a card. (define-struct card (value suit)) ;;A card is a structure (make-card v s), where v is an integer in the rang from 1 to 10 and s is a symbol from the set ‘hearts, ‘diamonds, ‘spades, and ‘clubs.
When comparing two cards to determine if one is larger than the other, we first consider the values of the cards. However, if the values of the cards are the same, then we use the suit of the card to determine which card is larger. The suits are ranked in the following order: spades is greater than hearts, hearts is greater than diamonds, and diamonds is greater than clubs.
a. Complete the function higher-suit. Suggestion: Carefully consider the order in which you check the suits of the cards ;;higher-suit: symbol symbol -> boolean ;;Purpose: Consumes s1 and s2 representing different suits of cards. Produces true when s1 is greater than s2 and false otherwise. ;;Examples: (higher-suit ‘spades ‘clubs) -> true ;; (higher-suit ‘diamonds ‘hearts) -> false (define (higher-suit s1 s2) ...)
b. Complete the function card>? that consumes two cards card1 and card2 (that do not both have the same value and same suit) and produces true when card1is greater than card2. Use higher-suit from part (a) in your solution. ;;card>?: card card -> boolean ;;Purpose: Produces true when card1 is greater than card2 and false otherwise. ;;Examples: ;;(card>? (make-card 3 ‘spades) (make-card 4 ‘diamonds)) -> false ;;(card>? (make-card 6 ‘hearts) (make-card 6 ‘clubs)) -> true (define (card>? card1 card2) ...)
c. Write two tests for that test different situations. Do not repeat the situations from the two provided examples.
6. Complete the function suit-count that consumes a list of card structures and a suit and produces the total value of the cards in the list that match the given suit. Refer to the card structure and data definitions in question 5. ;; Data for examples (define h3 (make-card 3 ‘hearts)) (define h4 (make-card 4 ‘hearts)) (define c3 (make-card 3 ‘clubs)) (define hand (cons h3 (cons c3 (cons h4 empty)))) ;;suit-count: (listof card) symbol -> nat ;;Purpose: Produces the sum of the values of the cards in the loc that have a suit that matches s. ;; Examples: ;; (suit-count hand ‘hearts) -> 7 ;; (suit-count hand ‘diamonds) -> 0 ;; (suit-count empty ‘hearts) -> 0 (define (suit-count loc s) ...)
7. Suppose the following helper function has been written for you. Do not write this helper function but do read the contract and purpose carefully. ;;is-perfect?: nat -> boolean ;;Purpose: Produces true when value is a perfect square and false otherwise. ;;Examples:
;;(is-perfect? 0) -> true ;;(is-perfect? 4) -> true ;;(is-perfect? 5) -> false (define (is-perfect? Value) ...) Using the helper function is-perfect?, complete a function perfect-squares that consumes a list of integers and produces a list that contains all elements from the original list that are perfect squares. Note that negative integers cannot be perfect squares. ;;perfect-squares: (listof int) -> (listof nat) ;;Purpose: Produces a list of integers containing the elements from original that are perfect squares. ;;Examples: ;;(perfect-squares (cons -1 (cons 0 (cons 1 (cons 2 (cons 3 (cons 4 empty))))))) -> (cons 0, (cons 1 (cons 4 empty))) ;;(perfect-squares (cons 5 empty)) -> empty (define (perfect-squares original) ...)
8. Zoos record information about every type of animal in the zoo: the kind of animal (e.g. zebra), how many of this animal live at the zoo and which of the four zones is home to the animal (Desert, Forest, Arctic or Ocean) The Waterloo co-‐op student working at the zoo writes the following structure definition and data definition: (define-struct animal-info (kind how-many zone)) ;; An animal-info is a (make-animal-info k h z) structure where ;; k is a string representing the kind of animal ;; h is a natural number representing the number of animals of this kind ;; z is a symbol ‘Desert, ‘Forest, ‘Arctic, or ‘Ocean
a. What is the advantage of defining this structure instead of working with strings, numbers and symbols separately?
b. List the names of the functions that are automatically generated when the structure definition is entered into Dr. Racket.
c. What is the purpose of having this data definition? d. As you can see, the student decided to use symbols for the zone field instead of using strings.
Briefly justify the student’s choice.
Answers to Practice Questions: 1. What does each expression produce?
a. 25 b. error (extra brackets around (-‐ 5 1)) c. false d. false e. false f. error (cannot compare a string to a number using >) g. ‘z h. error (cannot take the rest since (first mylist) is not a list)
2. Full trace: a. (* (-‐ a (+ a 1)) 2)
-‐> (* (-‐ 5 (+ a 1)) 2) -‐> (* (-‐ 5 (+ 5 1)) 2) -‐> (* (-‐ 5 6) 2) -‐> (* -‐1 2) -‐> -‐2
b. (cond [(> 3 4) (+ 2 2)] [(> 5 4) “a2”] [else ‘a3]) -‐> (cond [false (+ 2 2)] [(> 5 4) “a2”] [else ‘a3]) -‐> (cond [(> 5 4) “a2”] [else ‘a3]) -‐> (cond [true “a2”] [else ‘a3]) -‐> “a2
3. Answer Yes or No a. Yes b. No c. No d. Yes e. No f. No g. Yes h. Yes
4. a. ;;num-‐vowels: string -‐> (union int[>0] symbol) b. ;;Purpose: Consumes astring which is a string and produces the number of vowels in astring or
the symbol ‘vowel-‐free if the string contains no vowels. c. ;;Examples:
;;(num-‐vowels “computers”) -‐> 3 ;;(num-‐vowels “qrstuvwz”) -‐> ‘vowel-‐free ;;(num-‐vowels “123456”) -‐> ‘vowel-‐free
;;(num-‐vowels “”) -‐> ‘vowel-‐free ;;(num-‐vowels “aeiouaeiou”) -‐> 10
5. a. (define (higher-suit s1 s2)
(cond [(symbol=? S1 ‘spades) true] [(and (symbol=? S1 ‘hearts) (or (symbol=? S2 ‘diamonds) (symbol=? S2 ‘clubs))) true] [(and (symbol=? S1 ‘diamonds) (symbol=? S2 ‘clubs)) true] [else false]))
b. (define (card>? card1 card2) (cond [(> (card-value card1) (card-value card2)) true] [(= (card-value card1) (card-value card2)) (higher-suit (card-suit card1) (card-suit card2))] [else false]))
c. ;;Tests for card>?: (check-expect (card>? (make-card 8 ‘clubs) (make-card 8 ‘diamonds)) false) (check-expect (card>? (make-card 9 ‘hearts) (make-card 3 ‘spades)) true)
6. (define (suit-count loc s) (cond [(empty? loc) 0] [(symbol=? S (card-suit (first loc))) (+ (card-value (first loc)) (suit-count (rest loc) s))] [else (suit-count (rest loc) s)]))
7. (define (perfect-squares original) (cond [(empty? original) empty] [(<(first original) 0) (perfect-squares (rest original))] [(is-perfect? (first original)) (cons (first original) (perfect squares (rest original)))] [else (perfect-squares (rest original))]))
8. Zoo Information: a. Defining this structure makes it easier to select parts of it (using selector functions)
later if needed. It organizes all of the data for future use. b. animal-info?
make-animal-info animal-info-kind animal-info-how-many animal-info-zone
c. The data definition is there so that you know what type of data to put in for each parameter. This way, proper data types (strings, symbols, numbers, etc.) will be able to be evaluated in any functions where they are used.
d. There are only four possibilities for the zone of the animal (Desert, Forest, Arctic, or Ocean). It is easier for Scheme to compare symbols than strings. Strings are used when the data will often be different (and there is a large variety of it).