Last active
December 28, 2019 10:18
-
-
Save DarinM223/ddaa87eadbd53970a7b4da42fb75d9d8 to your computer and use it in GitHub Desktop.
Compile time table in Racket and Common Lisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defmacro make-table (sym &rest kvs) | |
(let* ((hash-sym (gensym)) | |
(setters (iter (for (k v) in kvs) | |
(collect `(setf (gethash ,k ,hash-sym) ,v))))) | |
`(defmacro ,sym () | |
(let ((,hash-sym (make-hash-table))) | |
,@setters | |
,hash-sym)))) | |
(defmacro get-table (sym k) | |
(let ((hash (funcall (macro-function sym) nil nil))) | |
(gethash k hash))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket/base | |
(require syntax/parse/define (for-syntax racket/base racket/syntax threading)) | |
(define-simple-macro (make-table name:id (k:expr v:expr) ...) | |
#:with id (format-id #'name "get-table-hash-~a" (syntax-e #'name)) | |
(define-syntax id (~> (hash) (hash-set k v) ...))) | |
(define-syntax-parser get-table | |
[(_ name:id k:expr) | |
(define fn-name (format-id #'name "get-table-hash-~a" (syntax-e #'name))) | |
(define hash (syntax-local-value fn-name)) | |
(define value (hash-ref hash (eval (syntax-e #'k)))) | |
#`(#%datum . #,value)]) | |
(make-table table ('(1 2 3) "hello") ("hi" (+ 1 2))) | |
(get-table table '(1 2 3)) ; => "hello" | |
(get-table table "hi") ; => 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment