[racket] Numbers with dimensions

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sat Oct 26 11:05:29 EDT 2013


Wouldn't we want something like this: 

#lang racket

(module+ test (require rackunit))

(struct distance (value) #:transparent) ;; this should be abstract 
(struct yard distance () #:transparent)
(struct meter distance () #:transparent)

;; distance distance -> distance 

(module+ test
  (check-equal? (d+ (yard 1) (yard 2)) (yard 3))
  (check-equal? (d+ (yard 1) (meter 2)) (meter (+ .9 2)))
  (check-equal? (d+ (meter 1.8) (yard 1)) (yard (+ 2.0 1)))
  (check-equal? (d+ (meter 2) (meter 1)) (meter 3)))

(define (d+ d1 d2) 
  (match (list d1 d2)
    [(list (struct yard (value)) (struct yard (value2))) (yard (+ value value2))]
    [(list (struct yard (value)) (struct meter (value2))) (meter (+ (yard->meter value) value2))]
    [(list (struct meter (value2)) (struct yard (value))) (yard (+ (meter->yard value2) value))]
    [(list (struct meter (value)) (struct meter (value2))) (meter (+ value value2))]))

;; distance distance-constructor -> distance 

(module+ test 
  (check-equal? (conversion (yard 3) meter) (meter (* 3 .9))))

(define (conversion x d)
  (match x 
    [(struct yard (y)) (if (eq? yard d) x (meter (yard->meter y)))]
    [(struct meter (y)) (if (eq? yard d) (yard (meter->yard y)) x)]))


;; auxiliaries 
(define (yard->meter v) (* .9 v))
(define (meter->yard v) (/ v .9))

-- Matthias



On Oct 26, 2013, at 7:20 AM, Laurent wrote:

> Ok, so I just hacked together a small lib for handling numbers with unit symbols and exponents:
> 
> Quick example:
> > (measure->value
>    (m* '(18 s) 
>        '(1600 km (h -1))
>        '(1000 m (km -1))
>        '(1/3600 h (s -1))))
> '(8000 m)
> 
> You can get it with:
> $ raco pkg install measures
> or from the File menu in DrRacket, if you have a recent version of Racket (strictly > 5.3.6).
> 
> Examples and details here:
> https://github.com/Metaxal/measures
> 
> HTH,
> Laurent
> 
> 
> On Fri, Oct 25, 2013 at 12:51 AM, Alvin Schatte <AlvinSchatte at skytex.net> wrote:
> Is there a library or package that combines numbers and their operations with dimensions that may be associated with them?
> Alvin Schatte
> 
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
> 
> 
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20131026/71a60525/attachment.html>

Posted on the users mailing list.