[Top][All Lists]

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

Re: problem with macro definitions

From: hector
Subject: Re: problem with macro definitions
Date: Tue, 9 May 2017 10:14:35 +0200
User-agent: Mutt/1.5.20 (2009-06-14)

On Sat, Apr 29, 2017 at 06:06:32PM +0200, hector wrote:
> Thank you for your reply.
> On Sat, Apr 29, 2017 at 11:39:13AM +0200, Michael Heerdegen wrote:
> > hector <address@hidden> 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 know. In this case when the list is constant it seemed to be right.
> > > 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.
> Let me rephrase your statement:
> "You gain nothing when you write this as a macro.  In this
> implementation, the index is calculated at run-time"
> I'm aware of that now. This is not what I meant.
> I'll try to rewrite it.

I did it. This is what I meant:

(defmacro idx (list needle)
  (let (found
        (haystack (eval list))
        (idx 0))
    (while (not found)
      (when (eq (car haystack) needle)
        (setq found idx))
      (setq idx (1+ idx))
      (setq haystack (cdr haystack)))

The macro expansion is just a number.
I come from C. I know each language has its idioms.
I don't know if this is good LISP. But I was just trying
to get the equivalent of a C enum. In most cases it can
be achieved with symbols but in this case I needed the
integer. With the improvement that I don't traverse the
whole list, just until the element (needle) is found.

I'm not quite sure what the "(let ((haystack (eval list))))"
does but it works.

reply via email to

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