help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: defining many similar functions using macros


From: David Kastrup
Subject: Re: defining many similar functions using macros
Date: Sun, 03 Oct 2004 10:18:36 +0200
User-agent: Gnus/5.1006 (Gnus v5.10.6) Emacs/21.3.50 (gnu/linux)

Joe Corneli <jcorneli@math.utexas.edu> writes:

> I have a lot of functions that are very similar:
>
> (defun tex-alpha ()
>   (interactive)
>   (insert "\\alpha"))
>
> (defun tex-beta ()
>   (interactive)
>   (insert "\\beta"))
>
> ...
>
> I would like to define them all in one go:
>
> (dolist (elt '("alpha"
>                "beta"
>                ...))
>   (define-tex-symbol elt))
>
> This seems like a good chance to use a macro.

Not really.

> My first experiment along these lines fails however, and I could use
> some help re-designing it.
>
> This macro works on single elements:
>
> (defmacro define-tex-symbol (name)
>   `(defun ,(intern (concat "tex-" name)) ()
>      (interactive)
>      (insert "\\" ,name)))
>
> E.g. (define-tex-symbol "alpha") ;=> tex-alpha
>
> But 
>
> (dolist (elt '("alpha"
>                "beta"))
>   (define-tex-symbol elt))
>
> triggers an error:
>
> Debugger entered--Lisp error: (wrong-type-argument sequencep elt)
>   concat("tex-" elt)
>   (intern (concat "tex-" name))
>   (list (quote defun) (intern (concat "tex-" name)) nil (quote (interactive)) 
> (list (quote insert) "\\" name))
> ...
>
> There seem to be some subtleties associated with macro expansion
> that I'm missing here.

Nothing subtle here at all. macros are substitutions at compile time
(that's why they are efficient).  So the "intern" gets evaluated at
compile time.  At that time, `name' is bound to the unevaled symbol
`elt'.  So what defun would you expect to result from your code?
Really.  Take pencil and paper and write down the expansion you wanted
to occur.  You can't calculate the symbol to define at compile time,
because it is supposed to be a different one each time through the
loop.

-- 
David Kastrup, Kriemhildstr. 15, 44793 Bochum


reply via email to

[Prev in Thread] Current Thread [Next in Thread]