This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

need help with with-open-file() style macro

3 posts · 3136 views

Ayup, I'm trying to create a macro binding a symbol in the same manner as with-open-file():
(defmacro with-experiment ((experiment file) &body body)
  `(let* ((,experiment (read-experiment-file ,file)))
     ,@body))
This works but I'm a bit worried that "file" is evaluated before "experiment", but is this even a valid concern? with-open-file() and this code doesn't handle a non-symbol argument in this position.

Anybody know of any pitfalls in this regard?

-a

Re: need help with with-open-file() style macro

This only matters in cases where you don't specify the order of evaluation in your documentation and it violates the principle of least surprise.

You are using experiment purely as a name, don't worry about it :)

Re: need help with with-open-file() style macro

Backquote replaces ,experiment by the value of the variable experiment. The value itself (that is, the actual argument to the macro) isn't evaluated.

The code
(with-experiment ((car ex) "file")
  ...)
will be replaced by
(let* (((car ex) (read-experiment-file "file)))
  ..)
which causes an error from let* because (car ex) isn't a symbol. But (car ex) wont be evaluated.

Since it can be confusing if an error is issued by let* though there is no let* in the source code your macro will become more user friendly if you add a check-type:
(defmacro with-experiment ((experiment file) &body body)
  (check-type experiment symbol)
  `(let* ((,experiment (read-experiment-file ,file)))
     ,@body))