;; 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))) #| ; Union Types -- intro ; ; - What is the type of (the signature of)... ; a. string=? : ... ; b. string? : ... ; ; - What are the steps of the design recipe [complete the 3 lines] ; ;;; Per-function: ; 4. ; 5. ; 7. ; 8. Watch your tests pass, and celebrate! ---- per function: 4. write tests 5. stub: signature, purpose-statement, header, stub 7. complete the function-body 8. watch your tests pass |# ; Datatype definition: ; A *course-result* is: ; - a number in [0.0,4.0], (interpretation: grade) OR ; - 'incomplete, (interpretation: 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 to take it in future) ; We say this is a "union type, with 4 variants". ; Give several examples of the data. ; Task: write a function to determine if a student can register itec220 (CS2), ; given their course-result from itec120 (CS1). ; Policy: you are allowed to register for itec220 if you got a C or better (2.0), ; or if you're currently-enrolled, or if you have an unresolved-incomplete, ; but not if you're just enrolled in CS1 for *next* semester. #| ; Data Def'n: A taxable income is either: ; - a real number in (-∞, 0] (interpretation: a loss), OR ; - a real number in (0, 9950] (interpretation: a modest income), OR ; - a real number in (9950,40525] (interpretation: a middle income), OR ; - a real number in (40525,86375] (interpretation: a moderately-high income) ; - a real number in (86375,∞) (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) ; ($9950 => 10%; $40525 => 12%; else 22% ) ; https://taxfoundation.org/2021-tax-brackets ; examples of the data: ; func-for-taxable-income : taxable-income -> ?? ; (define (func-for-taxable a-ti) (cond [... ...] [... ...] [... ...] [... ...])) ; Task: Write a function to return the tax-due, given taxable-income. ; TODO: Step 4: develop test cases: (check-expect (tax -30) 0) (check-expect (tax 0) 0) (check-expect (tax 10) 1) (check-expect (tax LO) (* LO 0.10)) (check-expect (tax (+ LO 1.00) (+ (* LO 0.10) 0.12)) (check-expect (tax (+ LO 0.01) (+ (* LO 0.10) 0.0012)) (check-expect (tax (+ LO 1000) ...) (check-expect (tax MED) ...) (check-expect (tax (+ MED 10000)) ...)) ; tax : number -> number ; return the tax-due, given taxable-income `a-ti`. ; (for single tax-payers; we'll stop after 3 tax-tiers) ; #| ; An alternate implementation: ; 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 9950) (* 0.10 income)] [(<= income 40525) (+ (* 0.10 9950) (* 0.15 (- income 9950)))] [else (let* {[tier2 (- 40525 9950)] [excess (- income 40525)]} (+ (* 0.10 9075) (* 0.15 tier2) (* 0.25 excess)))])) |# ; Update: ; a taxable-income-entry is either: ; - 'exempt (interpretation: income is exempt-- tax-treaty?), OR ; - #false (interpretation: no taxes filed!), OR ; - a real number in (-∞, 0] (interpretation: a loss), OR ; - a real number in (0, 9950] (interpretation: a modest income), OR ; - a real number in (9950,40525] (interpretation: a middle income), OR ; - a real number in (40525,∞) (interpretation: a high income) ; ; What do you think of *this* data-def'n? ; 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 9950)) ...] [... ...] [... ...]))) ; (**) 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 9950) ...] [.. ..] [.. ..]) ; 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 course-result is: ; - a number in [0.0,4.0], (interpretation: grade) OR ; - 'incomplete, (interpretation: 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 to take it in future) ; ; Task: write a function to determine if a student can register itec220 (CS2), ; given their course-result from itec120 (CS1). ; Policy: you are allowed to register for itec220 if you got a C or better (2.0), ; or if you're currently-enrolled, or if you have an unresolved-incomplete, ; but not if you're just enrolled in CS1 for *next* semester. ; Datatype definition: ; - 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). ; Datatype definition: ; A column-determiner is: ; - a character (char to split by), OR ; - a positive-int (the column-width ; path-or-string ; regexp-or-string ; /usr/sbin/periodic uses a configuration-file entry to determine how it handles output: ; ; - If this is set to a path name (beginning with a `/' character), output is simply logged to that file. ; - If this value does not begin with a `/' and is not empty, it is assumed to contain a list of email ; addresses, and the output is mailed to them. ; - If this value is the empty string (or, is not set), output is sent to standard output. ; A Student is: ; - 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 (interpretation: the address exists, but is unknown to us). ; 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) ; ; Note that in this case, all three variants might be denoting the same underlying info. ; And in real code, you'd want your code to have one "canonical" way it represents ; the info, along with functions to do a "one time" translation the other variants ; into your preferred representation. ; ; E.g., you might use java.util.Date pretty much everywhere in your code base, ; and then have a Date constructor that took in an string "yyyy-mm-dd", ; and a constructor that took in an int(day-of-current-year). ; This doesn't really need a full union-type, BUT it can sure be convenient ; if your clients can pass any of those three into your functions ; (without making them have to call the `Date` constructor themselves). ; ; This accounts for SOME uses of union-types, but not all. ; 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 list-of-directories (a "path"), 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) ; A number-of-allowed-occurrences is: ; - a number (interpretation: the one allowed number), ; - a pair of numbers (interpretation: an interval -- min and max) ; - a list-of-intervals (interpretation: allow the union of the intervals) ; - an indicator function (interpretation: allow a number if the function returns #true when given that number) ; ; E.g. an auto-grader for hw counts #occurs of "sqrt", and ; might want exactly 3, or between 2 and 5, or either 2-5 or 7-9, or a prime-number-of-occurrences. |# #| 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 (by mentioning them in comments) Some statically-typed languages DO let you define union-types. (ML, Ada's "variant record", Haskell) |# #| ; Another example, worked out: enumerated types. ; (But it's not a very exciting example.) ; Task: `turn`, for changing a stop-light. ; ...wait, what data type to use? ; Data Definition: ; A slc ("stoplight color") is one of: ; - 'red, (interpretation: stop) OR ; - 'yellow (interpretation: 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) ...] )) |#