Page 1 of 1

Templates

Posted: Thu Aug 23, 2007 8:10 pm
by 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:

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

Posted: Thu Aug 23, 2007 10:44 pm
by Lutz
look into 'expand' and 'letex' to do similar things.

Lutz

Posted: Thu Aug 23, 2007 11:07 pm
by Jeff
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.