Page 1 of 1

Simple macros

Posted: Thu Jul 09, 2009 1:37 pm
by hsmyers
Are there advantages/dis-advantages to implementing simple one-liners as macros? For instance

Code: Select all

 (define (even? n)
   (zero? (% n 2)))
versus the macro definition.

--hsm[/code]

Posted: Thu Jul 09, 2009 8:01 pm
by Kazimir Majorinc
Do you think on something like:

(define-macro (evenm? n) (zero? (% (eval n) 2)))


I think macros should be used only if one cannot use functions. The functions are slightly shorter, faster (in this case 20%) and probably easier to manipulate by meta-code. For example, for with existing syntax cannot be defined as function because (for (i 1 100) ... ) would return error trying to evaluate (i 1 100). Logical operation or can be defined as function, but if you want or to be lazy, i.e. it stops evaluating after first non-nil argument, then you need macros.

In this case, I think function is better choice.

Why easier to manipulate by meta-code? For example, I wrote debug-wrap to help me with debugging.

Code: Select all

(load "http://www.instprog.com/Instprog.default-library.lsp")

(define (evenf? n) (zero? (% n 2)))
(define-macro (evenm? n) (zero? (% (eval n) 2)))

(debug-wrap evenf?)
(debug-wrap evenm?)

(set 'x 44)

(evenf? x)

; Output:
;
; (evenf? (in 44)
;         (out true)); t=0, mem=3, sym=0
;
        
(evenm? x)

; (evenm? (in x)
;         (out true)); t=0, mem=3, sym=0
;

(exit)
Macro output is less useful because evenm? really recives x as argument, and not evaluated x as evenf?.

Posted: Thu Jul 09, 2009 8:46 pm
by hsmyers
I like your rule of "macros should be used only if one cannot use functions". I think that this is where programmers coming from other languages and more C/C++ style 'macros' possibly get confused. They are thinking of text replacement where as lisp is more like language replacement.


--hsm