Simple macros

Started by hsmyers, July 09, 2009, 06:37:58 AM

Previous topic - Next topic

hsmyers

Are there advantages/dis-advantages to implementing simple one-liners as macros? For instance
(define (even? n)
   (zero? (% n 2)))

versus the macro definition.



--hsm[/code]
\"Censeo Toto nos in Kansa esse decisse.\"—D. Gale \"[size=117]ℑ♥λ[/size]\"—Toto

Kazimir Majorinc

#1
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.


(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?.
http://kazimirmajorinc.com/\">WWW site; http://kazimirmajorinc.blogspot.com\">blog.

hsmyers

#2
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 \"[size=117]ℑ♥λ[/size]\"—Toto