Match Patterns & Test Review
Table of Contents
1. Test Review
-
Question 1
Q: Write the racket expression that applies a function named mix-otgether to the arguments “peanut-butter” and “pickles”.
A: (mix-together “peanut-butter” “pickles”)
-
Question 2
Q: Write two test cases(using check-equal?) for the threes-in-number function, that accepts an integer and returns the number of occurrences of the digit ’3’
Too Lazy… Test
…
-
Question 4
Answer
A = {apple, pear, orange}
B = {banana}
AUB = {apple, pear, orange, banana}
three elements that can be in the set for a choice of it being in or not.
23
2*2*2 = 8
2. Match Patterns and Examples
; takes in a list of number ; returns a list where all the ; numbers are doubled ; double all the numbers in the given list (define (double[list: (Listof Real)]) : (Listof Real) (match lst ['() '()] [(cons f r) (cons (* f 2)) (double r)])) (check-equal? (double '(1 2 3) '(2 4 6)) (check-equal? (double '()) '()) (check-equal? (double '(0 -5 102)) '(0 -10 204))
How Double Works
(double ’(10 20)) -> not empty so assigns f to 10 and r to 20
=(cons (* 2 10) (double ’(20))) -> form a cons with doubling 10 and calling double on ’(20)
=(cons 20 (double ’(20)))
=(cons 20(cons (* 2 20) (double ’())))
=(cons 20 (cons 40 (double ’())))
=(cons 20 (cons 40 ’()))
Match Patterns | Examples |
---|---|
(struct name <pat> …) | (cons f r), (person n m f), (desk w d h) |
<constant> | ’(), 5, “hello”, ’empty, … |
identifier patterns <id> | f, r, anythin-else |
(? <expr> <put>) | (? even? f) |
(define (func [lst : (listof Integer)]) (match lst [(cons fst (cons scnd (cons thrd rst))) "There is exactly three elemnts in this list."]))
(define (func [lst : (listof Integer)]) (match lst [(cons (? even? f) r) (format "first value is even: ~v" f)] [(cons fst (cons scnd (cons thrd rst))) "There is exactly three elemnts in this list."]))
Matches that fall off the end ERROR
- add an identifer, [(other) … ]