Skip to content

Instantly share code, notes, and snippets.

Created September 21, 2023 23:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
lecture 8/contracts
#lang racket
(module temperature racket
#; {type Temperature}
[builder (->i ([t real?] [s (or/c "F" "K")])
#:pre (t s)
(or (and (equal? s "F") (>= (+ (/ (- t 32) 1.79999999) 273.15) 0))
(and (equal? s "K") (>= t 0)))
(r temperature?))]
[builder (-> real? (or/c "F" "K") temperature?)]
[temp< (-> temperature? temperature? boolean?)]))
;; ---------------------------------------------------------------------------
(define (temperature? x)
(or (F? x) (K? x)))
(struct F [n] #:prefab)
(struct K [n] #:prefab)
;; A Temperature (measurement) is one of:
;; - (F Rational) ;; represents Fahrenheit
;; - (K PositiveRational) ;; represents Kelvin
(define (builder t s)
[(equal? s "F") (F t)]
[(equal? s "K") (K t)]))
;; ---------------------------------------------------------------------------
#; {Temperature Temperature -> Boolean}
(define (temp< s t)
(match* (list s t)
[(list (F f) (F g)) (< f g)]
[(list (K k) (K l)) (< k l)]
[(list x y) (temp< (normalize x) (normalize y))]))
;; ---------------------------------------------------------------------------
#; {Temperature -> Temperature}
(define (normalize t)
(match t
[(K k) t]
[(F f) (K (+ (/ (- f 32) 1.79999999) 273.15))])))
(module client racket
(require (submod ".." temperature))
(printf "~a should be true" (temp< (builder 1 "K") (builder 1 "C")))
(printf "~a should be false" (temp< (builder 1 "K") (builder 1 "K"))))
(require 'client)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment