Skip to content

Instantly share code, notes, and snippets.

@NalaGinrut
Last active December 21, 2015 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NalaGinrut/6338046 to your computer and use it in GitHub Desktop.
Save NalaGinrut/6338046 to your computer and use it in GitHub Desktop.
a Python3 style string-template for Scheme
(define *stpl-SRE* '(or (=> dollar "$$")
(: "${" (=> name (+ (~ #\}))) "}")))
(define (make-string-template str . opts)
(define ll '())
(define lv '())
(define template
(irregex-replace/all
;;"(\\$\\{([^$])+\\})"
*stpl-SRE* str
(lambda (m)
(if (irregex-match-substring m 'dollar)
"$"
(let* ((key (symbol->keyword (string->symbol
(irregex-match-substring m 'name))))
(v (kw-arg-ref opts key)))
(and v (set! lv (cons (cons key v) lv))) ; default value
(set! ll (cons key ll))
"~a")))))
(lambda args
(let ((vals (map (lambda (x) (or (kw-arg-ref args x) (assoc-ref lv x) "NONE")) ll)))
(format #f "~?" template (reverse vals)))))
@NalaGinrut
Copy link
Author

(define tpl (make-string-template "${name1}, I'm ${name2}"))
(tpl #:name1 "madam" #:name2 "adam")
==> "madam, I'm adam"

and for default value

(define tpl (make-string-template "${name1}, I'm ${name2}" #:name1 "Dassy"))
(tpl #:name2 "adam")
==> "Dassy, I'm adam"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment