diff --git a/utils-tests.rkt b/utils-tests.rkt new file mode 100644 index 0000000..2ab79c4 --- /dev/null +++ b/utils-tests.rkt @@ -0,0 +1,16 @@ +#lang typed/racket + +;;; Tests for dds/utils. + +(require typed/rackunit "utils.rkt") + +(test-begin + (test-case "auto-hash-ref/explicit" + (let ([mytable #hash((a . 3) (b . 4))]) + (check-equal? (auto-hash-ref/explicit (mytable b a) + (* a b)) + 12)) + (let ([ht #hash((a . #t) (b . #f))]) + (check-equal? (auto-hash-ref/explicit (ht a b) + (and (not a) b)) + #f)))) diff --git a/utils.rkt b/utils.rkt new file mode 100644 index 0000000..34d3df5 --- /dev/null +++ b/utils.rkt @@ -0,0 +1,27 @@ +#lang typed/racket + +;;; dds/utils + +;;; Various utilities. + +(require (for-syntax syntax/parse)) + +(provide auto-hash-ref/explicit) + +;;; HashTable Injection + +;;; This section of the file contains some utilities to streamline the +;;; usage of hash tables mapping symbols to values. The goal is +;;; essentially to avoid having to write explicit hash-ref calls. + +;;; Given a (HashTable Symbol a) and a sequence of symbols, binds +;;; these symbols to the values they are associated to in the hash +;;; table, then puts the body in the context of these bindings. +(define-syntax (auto-hash-ref/explicit stx) + (syntax-parse stx + [(_ (ht:id xs:id ...) body:expr) + #`(let #,(for/list ([x (syntax->list #'(xs ...))]) + #`[#,x (hash-ref ht '#,x)]) + body)])) + +