Simple macros

Notices and updates
Post Reply
hsmyers
Posts: 104
Joined: Wed Feb 20, 2008 4:06 pm
Location: Boise, ID, USA
Contact:

Simple macros

Post 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]
"Censeo Toto nos in Kansa esse decisse."—D. Gale "ℑ♥λ"—Toto

Kazimir Majorinc
Posts: 388
Joined: Thu May 08, 2008 1:24 am
Location: Croatia
Contact:

Post 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?.

hsmyers
Posts: 104
Joined: Wed Feb 20, 2008 4:06 pm
Location: Boise, ID, USA
Contact:

Post 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
"Censeo Toto nos in Kansa esse decisse."—D. Gale "ℑ♥λ"—Toto

Post Reply