Skip to content

Instantly share code, notes, and snippets.

@sentientmonkey
Created August 23, 2017 06:37
Show Gist options
  • Save sentientmonkey/bafd18d52af9a3d0d71b6bf70f85a566 to your computer and use it in GitHub Desktop.
Save sentientmonkey/bafd18d52af9a3d0d71b6bf70f85a566 to your computer and use it in GitHub Desktop.
#lang racket/base
(require racket/match)
(provide convert-temperature celsius fahrenheit kelvin temperature-value temperature-unit)
(struct celsius (value) #:transparent)
(struct fahrenheit (value) #:transparent)
(struct kelvin (value) #:transparent)
(define (temperature-value temp)
(match temp
[(celsius value) value]
[(fahrenheit value) value]
[(kelvin value) value]))
(define (temperature-unit temp)
(match temp
[(celsius _) 'celsius]
[(fahrenheit _) 'fahrenheit]
[(kelvin _) 'kelvin]))
(define (celsius->fahrenheit value)
(+ 32.0 (* 1.8 value)))
(define (fahrenheit->celsius value)
(/ (- value 32.0) 1.8))
(define (kelvin->celsius value)
(- value 273.15))
(define (celsius->kelvin value)
(+ value 273.15))
(define (to-celsius-value temp)
(match temp
[(celsius value) value]
[(fahrenheit value) (fahrenheit->celsius value)]
[(kelvin value) (kelvin->celsius value)]))
(define (convert-temperature temp to-unit)
(let ([value (to-celsius-value temp)])
(match to-unit
['celsius (celsius value)]
['fahrenheit (fahrenheit (celsius->fahrenheit value))]
['kelvin (kelvin (celsius->kelvin value))])))
(module+ test
(require rackunit rackunit/text-ui)
(define-check (check-temperature? temp value unit)
(check-= (temperature-value temp) value 0.01)
(check-equal? (temperature-unit temp) unit))
(check-temperature?
(convert-temperature (celsius 0.0) 'celsius) 0.0 'celsius)
(check-temperature?
(convert-temperature (fahrenheit 0.0) 'fahrenheit) 0.0 'fahrenheit)
(check-temperature?
(convert-temperature (kelvin 0.0) 'kelvin) 0.0 'kelvin)
(check-temperature?
(convert-temperature (celsius 0.0) 'fahrenheit) 32.0 'fahrenheit)
(check-temperature?
(convert-temperature (celsius 100.0) 'fahrenheit) 212.0 'fahrenheit)
(check-temperature?
(convert-temperature (fahrenheit 32.0) 'celsius) 0.0 'celsius)
(check-temperature?
(convert-temperature (kelvin 283.15) 'celsius) 10.0 'celsius)
(check-temperature?
(convert-temperature (kelvin 300.0) 'fahrenheit) 80.33 'fahrenheit)
(check-temperature?
(convert-temperature (kelvin 283.15) 'celsius) 10.0 'celsius))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment