Templates

For the Compleat Fan
Locked
Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Templates

Post 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 :)
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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

Lutz

Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Post 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.
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Locked