Templates

Started by Jeff, August 23, 2007, 01:10:07 PM

Previous topic - Next topic

Jeff

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:


(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)


'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 :)
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

Lutz

#1
look into 'expand' and 'letex' to do similar things.



Lutz

Jeff

#2
Yes, I have used them quite a bit.  But they are not very concise and require that the symbols match.  In practical use, that is not often convenient.  Having a simple template syntax makes it easier to visualize what I am doing.
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code