Templates
Posted: Thu Aug 23, 2007 8:10 pm
One thing that I feel newLisp lacks is templates. In common lisp, you can use backticks to create form templates to simplify metaprogramming. I wrote a quick macro to permit something similar using underscores in newLisp:
'test-fn is an example of a function template. Using (template 'form 'expr-1 'expr-2 'expr-3 ...), the macro expands the template by replacing the left-most '_ with the evaluated 'expr-n. It then returns the unevaluated form.
It is almost completely untested but it sure looks pretty :)
Code: Select all
(define-macro (template)
(let ((form (args 0)) (syms (rest (args))))
(if (symbol? form) (set 'form (eval form)))
(cond ((empty? syms) form)
(true
(begin (nth-set (form (ref '_ form)) (eval (first syms)))
(if (rest syms)
(eval (cons 'template (cons form (rest syms))))
form))))))
(set 'test-fn '(define (_) (println _)))
(set 'some-var "hello")
(set 'expanded
(template test-fn (sym (format "print-%s" some-var))
some-var))
(println expanded)
(eval expanded)
(print-hello)
It is almost completely untested but it sure looks pretty :)