Skip to content

Instantly share code, notes, and snippets.

@mfelleisen
Created September 21, 2023 23:52
Show Gist options
  • Save mfelleisen/8d1629a9f964156fe177759c69173143 to your computer and use it in GitHub Desktop.
Save mfelleisen/8d1629a9f964156fe177759c69173143 to your computer and use it in GitHub Desktop.
lecture 8/contracts
#lang racket
(module temperature racket
(provide
#; {type Temperature}
temperature?
(contract-out
[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)
(cond
[(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