;; The first three lines of this file were inserted by DrScheme. 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 type_errors) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ;; Using symbols to handle type errors ;; Passing a wrong type of data to a function - type error ;(* 'Yes 'No) ;; Contract: number -> number ;; Purpose: determine a yearly interest rate based on amount ;; The interest rate is 0.04 for amounts between 0 and ;; 1000 (incl), 0.045 for amounts between 1000 and 5000 (incl), ;; and 0.05 for larger amounts. ;; Examples: (interest-rate 500) -> 0.04 ;; (interest-rate 1000) -> 0.04 ;; (interest-rate 10000) -> 0.05 (define (interest-rate amount) (cond [(< amount 0) 0.0] [(<= amount 1000) .04] [(<= amount 5000) .045] [(> amount 5000) 0.05] ) ) ;(interest-rate 'yes) ; a type error for < ;; A modified version that checks for wrong data type: ;; Contract: number -> number ;; Purpose: determine a yearly interest rate based on amount ;; The interest rate is 0.04 for amounts between 0 and ;; 1000 (incl), 0.045 for amounts between 1000 and 5000 (incl), ;; and 0.05 for larger amounts. ;; Examples: (interest-rate 500) -> 0.04 ;; (interest-rate 1000) -> 0.04 ;; (interest-rate 10000) -> 0.05 (define (interest-rate2 amount) (cond [(not (number? amount)) 'AmountIsNotANumber] [(< amount 0) 'NegativeAmount] [(<= amount 1000) .04] [(<= amount 5000) .045] [(> amount 5000) 0.05] ) ) (interest-rate2 -77) ;; expected value 'NegativeAmount (interest-rate2 true) ;; expected value 'AmountIsNotANumber (interest-rate2 2000) ;; expected value 0.045 ;; other functions that check for types (boolean? true) (boolean? 'true) (number? -0.98) (number? (+ 4 -77)) (number? 4/3) (integer? 3.14) (real? 3.14) (integer? 8/2) (exact? 3.14) (exact? 8/2) (exact? 1/3) (exact? (sin 5)) (exact? (ceiling (sin 5))) (symbol? 'yes) (symbol? 5) (symbol? "yes")