;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname union-type-intro-before) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) #| ; quick-quiz -- you do NOT need to re-state the question; ; just give the problem-numbers (e.g. "II.b.") and their answers: ; ; I. What row#,column# are you seated in (in that order)? ; (...I will count off row@ and column numbers shortly). ; ; II. What is the type of (the signature of)... ; a. string=? : string, string -> boolean ; b. string? : ANY -> boolean ; ; III. What are the steps of the design recipe [complete the 3 lines] ; ;;; Per-function: ; 4. ; 5. ; 7. ; 8. Watch your tests pass, and celebrate! Quiz: What are the steps of the design recipe? Take 1, when dealing with primitive types: ---- per function: 4. write tests 5. stub: signature, purpose-statement, header, stub 7. complete the function-body 8. watch your tests pass |# ; TASK: ; ; Data definition: a "username" is: ; a string of one or more lowercase roman letters (possibly followed by digits), ; whose length is in [1,14) ; (interpretation: the characters in the username (duh)) ; ; Give some examples of this data-type. ; Optional [we'll skip it]: ; Write `username?` ; [hint: use regexp, as a bit of hack, since we haven't discussed loops] ;; Data definition: A "lookup-result" is one of: ;; - a username (interpretation: RU username of an existing student), OR ;; - #false (interpretation: no such person found), OR ;; - 'private (interpretation: person exists, but information is non-public). ; Let's give several examples of this type of data: #| ;; 'lookup-result' is an example of a "union data type" -- using the word "OR", ;; `cond` is the natural way to handle a union data type. Write a function which, given a lookup-result, returns a string: either - a radford email address (e.g. “ibarland@radford.edu”), OR - “No such person.”, OR - “Information not published.”. |# (check-expect (lookup-result->string #false) "No such person.") (check-expect (lookup-result->string 'private) "Information not published.") (check-expect (lookup-result->string "ibarland") "ibarland@radford.edu") ; lookup-result->string : lookup-result -> string ; Return a end-user-friendly string representation of `a-lr` (define (lookup-result->string a-lr) (cond [(string? a-lr) ...] [(boolean? a-lr) ...] [(symbol? a-lr) ...])) ;; Aside: The syntax of `cond`: ;; Now let's write a function which takes in a lookup-result, ;; and just returns whether this is a known student. ;; (check-expect (known-student? "ibalrand") #true) (check-expect (known-student? #false) #false) (check-expect (known-student? 'private) #true) ; known-student? : lookup-result -> boolean ; returns whether this is a known student. ; (define (known-student? a-lr) (cond [.. ..] [.. ..] [.. ..])) #| Now, let's write a function which takes in a lookup-result, and ...[???]... |# ; func-for-lookup-result : lookup-result -> ??? ; (define (func-for-lookup-result a-lr) (cond [(string? a-lr) ...] [(false? a-lr) ...] [(symbol? a-lr) ...])) ; we will call the above the TEMPLATE for lookup-results. #| We actually just did several more steps of the design-recipe. 1. Make appropriate data definition (if needed). 2. Give some examples of that type of data 3. Template: a. If handling a union type, include a cond w/ one branch per option. ------- per function: 4. tests 5. stub : signature, header, purpose-statement, stub-body (copying template, if any) 7. complete the body-expression 8. watch your tests pass Note that if we write five more functions involving lookup-results, we only need do steps 1-3 once. (And we'll copy/paste 3a over and over, for each functions.) |# ; Task: `turn`, for changing a stop-light. ; ...wait, what data type to use? ; Data Definition: ; A slc ("stoplight color") is one of: ; - 'red, (interpreation: stop) OR ; - 'yellow (interpreation: stop-if-safe) , OR ; - 'green, (interpretation: go), OR ; - 'flashing-yellow (interpretation: proceed with caution), OR ; - 'flashing-red (stop, then proceed when safe) ;Examples of the data (duh): 'red 'yellow 'green 'flashing-yellow 'flashing-red (check-expect (turn 'red) 'green) (check-expect (turn 'green) 'yellow) (check-expect (turn 'yellow) 'red) (check-expect (turn 'flashing-red) 'flashing-red) (check-expect (turn 'flashing-yellow) 'flashing-yellow) ; turn : slc -> slc ; return the next color for a stop-light. ; (define (turn curr-color) (cond [(symbol=? curr-color 'red) 'green] [(symbol=? curr-color 'yellow) 'red] [(symbol=? curr-color 'green) 'yellow] [(symbol=? curr-color 'flashing-yellow) 'flashing-yellow] [(symbol=? curr-color 'flashing-red) 'flashing-red] [else (error 'turn "fell off cond?!")] ; It's already an error in beginning-student, to fall off the end of a cond. ; So I show this just for fun. (But in full-racket it's not an error, ; even when I wish it was, so in full-racket I *may* write such an `else`.) )) ; Task: write penalty-for-running-a-light. (check-expect (penalty-for-running-a-light 'red) 50) (check-expect (penalty-for-running-a-light 'yellow) 0) (check-expect (penalty-for-running-a-light 'green) 0) (check-expect (penalty-for-running-a-light 'flashing-yellow) 25) (check-expect (penalty-for-running-a-light 'flashing-red) 99) ; penalty-for-running-a-light : slc -> non-negative-real ; Return the fine for running a stoplight, in USD. ; (define (penalty-for-running-a-light curr-color) (cond [(symbol=? curr-color 'red) 50] [(symbol=? curr-color 'yellow) 0] [(symbol=? curr-color 'green) 0] [(symbol=? curr-color 'flashing-yellow) 25] [(symbol=? curr-color 'flashing-red) 99] )) ; Step 3, TEMPLATE, for ANY function processing a slc: ; func-for-slc : slc -> ??? (define (func-for-slc a-slc) (cond [(symbol=? a-slc 'red) ...] [(symbol=? a-slc 'yellow) ...] [(symbol=? a-slc 'green) ...] [(symbol=? a-slc 'flashing-yellow) ...] [(symbol=? a-slc 'flashing-red) ...] )) ; Data Def'n: A taxable income is either: ; - a real number in (-∞, 9525] (interpretation: a modest income), OR ; - a real number in (9525,38700] (interpretation: a middle income), OR ; - a real number in (38700,∞) (interpretation: a high income) ; Task: Write a function to return the tax-due, given taxable-income. ; (for single tax-payers; we'll stop after 3 brackets) ; ($9525 => 10%; $38700 => 15%; else 25% ) ; https://taxfoundation.org/2018-tax-brackets/ ; examples of the data: #| ; TODO: Step 4: develop test cases: (check-expect (tax 0) ..) (check-expect (tax 10) ..) (check-expect (tax 9525) ..) (check-expect (tax 9526) ..) (check-expect (tax 9525.01) ..) (check-expect (tax 36900) .. ) (check-expect (tax 47950) .. ) ; tax : number -> number ; return the tax-due, given taxable-income. ; (for single tax-payers; we'll stop after 3 tax-tiers) #| (define (tax income) (cond [(<= income 9525) (* 0.10 income)] [(<= income 36900) (+ (* 0.10 9525) (* 0.15 (- income 9525)))] [else (let* {[tier2 (- 38700 9525)] [excess (- income 38700)]} (+ (* 0.10 9075) (* 0.15 tier2) (* 0.25 excess)))])) ; Update: ; a taxable-income-entry is either: ; - 'exempt (interpreation: income is exempt-- tax-treaty?), OR ; - #false (interpretation: no taxes filed!), OR ; - a real number in (-∞, 9525] (interpreation: a modest income), OR ; - a real number in (9525,38700] (interpreation: a middle income), OR ; - a real number in (38700,∞) (interpreation: a high income) ; Examples of the data -- taxable-income-entry: 10000 37000.5 6000 'exempt #false ; template (define (function-for-tie a-tie) (cond [(symbol? a-tie) ...] [(false? a-tie) ...] [(and (real? a-tie) (<= a-tie 9525)) ...] [... ...] [... ...]))) ; (**) or, collapse the last three cases, and just say it's a "taxable-income" ; as previously defined? |# #| (define (func-for-taxable-income-entry a-tie) (cond [(symbol? a-tie) ...] [(boolean? a-tie) ...] [(<= a-tie 9525) ...] [.. ..] [.. ..]) ; DESIGN QUESTION: ; Should we make `tax2` call `tax` as a helper? ; I'd say, Answer: depending on our data-def'n: ; if we included 5 branches in 'taxable-income-entry', we should have 5 branches. ; Otherwise three. ; But that just begs the question: what is the right data-def'n -- ; should it have 'exempt,#f,taxable-income or should it have 5 branches? ; I tend towards the former. |# |# #| More examples of union types: ; - A String (interpretation: a first & last name), OR ; - a number (interpretation: an ID number). ; - A String (interpretation: a street-address in standard post-office format) OR ; - null (interpreation: the address exists, but is unknown to us). ; A course-result is: ; - a number in [0.0,4.0], (interpretation: grade) OR ; - 'incomplete, (interpreation: student has taken an incomplete, which hasn't expired) OR ; - 'in-progress, (interpretation: the course is currently in progress) OR ; - a string (interpretation: the planned semester) ; A card-rank is: ; - a natnum in 2..10 ; - one-of 'A, 'K, 'Q, 'J ; - 'Joker ; a color-spec is: ; - a string (interpretation: one of the standard css-color-names), OR ; - an struct with RGB fields (interpretation: red, green, and blue components of the color) ; a date is: ; - string, (interpretation; a date, in format "yyyy-mmm-dd"), OR ; - an int in 1..366, (interpretation: day-of-the-current-year) OR ; - a java.util.Date object (interpretation: Date -- see that class for details) ; a problem-report is: ; - an natnum (interpretation: an index into array of existing problem-tickets), OR ; - a string (interpretation: a new problem, to be submitted) - A file-or-fname is: - a string (interpretation: filename), OR - a file-descriptor (interpretation: the already-opened file) [ It's a real-world pain to have functions that want to open a file and work with it, and then call a helper-function which requires the filename ...] ; a transaction is: ; - double (interpretation: Cash transactions: Discount) ; - int (interpretation: Check transactions: CheckNumber) ; - string-and-two-ints (interpretation: Credit transactions: Card Number and Expiration Date) |# #| Thoughts on the uses of union-types (and what we did before hearing about them). NOTE that sometimes a sentinel value is used, but it has to be shoe-horned into the existing type-system: Consider java's String#indexOf -- what does it return for not-found? What might python/racket/javascript use instead? What might be a union-type, to describe the result? NOTE that if we have a type "T, OR ", in java we'll use a class, and use `null` to represent that one sentinel value. Examples: Map#get; This has its issues [SO easy to forget that a var declared to hold a `String` might not hold a string => Null Pointer Exception; what if `null` might be a valid-info instead of a sentinel, e.g. java.util.Map#get(U) leads to weird library principles like "you can't associate an object with `null`".] NOTE that Java can hack functions that take in a union-type, by overloading. However, they can't *return* something of a union-type. Dynamically-typed languages like javascript, python, racket use union-types routinely (mentioned in comments) Some statically-typed languages DO let you define union-types. (ML, Ada's "variant record", Haskell) Another type of a natural union-type: - a number, - a pair of numbers (an interval -- min and max) - a list-of-intervals - an indicator function E.g. an auto-grader for hw counts #occurs of "cond" (or of "["), and might want exactly 3, or between 2 and 5, or iether 2-5 or 7-9, or a multiple-of-3 |#