[Top][All Lists]

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

Re: problem with macro definitions

From: Michael Heerdegen
Subject: Re: problem with macro definitions
Date: Sat, 29 Apr 2017 11:39:13 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.0.50 (gnu/linux)

hector <> writes:

> I was looking for the complementary of nth, that is, a function that
> returns the index of an element. Since it can be done at compilation
> time

Not if you want to use it on values that are known only at run-time.

> I thought it was a good candidate for a macro:

No, not really:

> (defmacro idx (list telt)
>   `(let (found
>        (idx 0))
>      (dolist (elt ,list found)
>        (when (eq elt ,telt)
>        (setq found idx))
>        (setq idx (1+ idx)))))

You loose nothing when you rewrite this as a function.  In this
implementation, the index is calculated at run-time.

> Then I wrote another one:
> (defconst start-states '(initial red blue yellow))
> (defconst shift-val 10)
> (defmacro state-eof (st)
>   (let ((val (+ shift-val (idx start-states st))))
>     val))

That comes closer to what you intend to implement.

> Probably there is a better way to accomplish this. Anyway I'd like to
> know why it doesn't work.
> This yields 2 as expected:
> (idx start-states 'blue)
> so I expected this to return 12:
> (state-eof 'blue)

Note that macros don't evaluate their arguments.  The argument 'blue you
pass, a read syntax for (quote blue), is a list of two elements.  This
doesn't appear as an element of `start-states' which consists of four

Your macro `state-eof' actually does find the value at compile time.
It's still an unusual use case for `defmacro' which is normally code
transformation.  Your `state-eof' calls just expand to a number.  You
can do this, but in real life one would probably prefer a different
solution, like defining this number as a `defconst', depending on the
actual use case.



reply via email to

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