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

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

Re: elisp - anonymous function in an association list?


From: David Kastrup
Subject: Re: elisp - anonymous function in an association list?
Date: Thu, 29 Nov 2007 16:32:37 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.0.50 (gnu/linux)

apatheticagnostic <apatheticagnostic@gmail.com> writes:

> On Nov 29, 9:50 am, Marc Tfardy <m-t-o___CUT__IT...@web.de> wrote:
>> apatheticagnostic schrieb:
>>
>> > take, for example this code showing what I mean:
>>
>> > (defvar sample-alist '(("a" '(lambda ()
>> >                                 (message "We worked!")))
>> >                        ("b" #'(lambda ()
>> >                                 (message "B worked too!")))))
>>
>> > (defun test-call (x)
>> >   (funcall (cdr (assoc x sample-alist))))
>>
>> > (test-call "a")
>> > (test-call "b")
>>
>> > Both calls fail, with an error message like so:
>>
>> This seems to work:
>>
>> (defvar sample-alist '(("a" (lambda () (message "We worked!")))
>>                         ("b" (lambda () (message "B worked too!")))))

[fixed to omit the utterly pointless eval:]

>> (defun test-call (x)
>>    (funcall (car (cdr (assoc x sample-alist)))))

> So it does. Well, I feel dumb now. I assumed that I would need to
> quote the lambda expressions in some way to prevent them from being
> evaluated at definition.

lambda is self-quoting.  It is preferable not to quote it nevertheless,
because then the byte compiler can compile and optimize it.

However, that was not the problem.  The problem is that (cdr '(a b)) is
not b, but rather something equal to '(b).  So you either need to write

(defvar sample-alist '(("a" . (lambda () (message "We worked!")))
                       ("b" . (lambda () (message "B worked too!")))))

_or_ otherwise need the (cadr (assoc... rather than (cdr
(assoc... construct.
-- 
David Kastrup, Kriemhildstr. 15, 44793 Bochum


reply via email to

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