4 karma · joined May 2, 2017 (9y ago) · 3 submissions
comment 9y ago · link · parent
And yes, feel free to do anything with that example and share further. Not enough people have had exposure to Racket's implicit expansion macros. (Is that even what they're called?)
comment 9y ago · link · parent
I always imagined implementing string interpolation by overriding the implicit #%datum macro and checking for literal strings. Here's a quick (probably non-idiomatic) example for comparison.
#lang racket
(require
(rename-in racket (#%datum core-datum))
(for-syntax syntax/parse))
(define-syntax (#%datum stx)
(syntax-parse stx
[(_ . x:str) (interpolate #'x)]
[(_ . x) #'(core-datum . x)]))
(define-for-syntax (interpolate stx)
(define re #rx"@{[^}]+}")
(define (trim match) (substring match 2 (- (string-length match) 1)))
(define (to-stx val) (datum->syntax stx val))
(define (datum val) (to-stx (cons #'core-datum val)))
(define (source text) (to-stx (read (open-input-string text))))
(let* ([text (syntax->datum stx)]
[matches (regexp-match* re text)]
[template (datum (regexp-replace re text "~a"))]
[values (map (compose source trim) matches)])
(if (null? matches)
template
(to-stx `(,#'format ,template ,@values)))))
42 ;=> 42
#t ;=> #t
"1 time" ;=> "1 time"
(define foo 2)
"@{foo} times" ;=> "2 times"
"@{(+ foo 1)} times" ;=> "3 times"
(define (scoped foo)
(define (format . args) "boom!")
"@{foo} times")
(scoped 10) ;=> "10 times"