Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Another place where macros in Lisp fail is that they may evaluate an expression twice. (Using the Scheme dialect, because I don't write good enough CL.)

  (define (inc! x) (set! x (+ x 1)) x)
  
  (define-syntax-rule (square x) (* x x))

  (define n 5)
  (square (inc! n)) ;==> 42
This can be solved using a temporary variable as in the original article,

  (define-syntax-rule (skuare x) (let ([temp x]) (* temp temp)))

  (define m 5)
  (skuare (inc! m)) ;==> 42
But it's easier because you don't have to declare the type of temp. Also Scheme has hygienic macros, so you don't need to use gensym to avoid the variable capture of temp.


> Another place where macros in Lisp fail is that they may evaluate an expression twice

Strictly speaking, macros don't evaluate their expressions at all.

Square is a bad example, though. Macros are not for writing function-like expressions; they're for extending (or more generally transforming) the syntax of the language. Inline functions and compiler macros are more appropriate tools for things like square.


> Strictly speaking, macros don't evaluate their expressions at all.

OK, you are right.

A better example is a bad implementation of a short circuiting or:

  (define-syntax-rule (bad-or x y)
    (if x x y))
It can't be a function because sometimes you don't want to evaluate y, but in the resulting code x is sometimes executed twice.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: