(case) evaluation

Q&A's, tips, howto's
Locked
statik
Posts: 58
Joined: Thu Apr 14, 2005 1:12 am

(case) evaluation

Post by statik »

Can anyone tell me why the following is true:

Code: Select all

(setq a 1)
(setq b 2)
(setq c 3)
(setq d 1)

(case d
   (a (do-this))
   (b (do-that))
   (c (do-something))
   (true)
)

=> nil
I understand that the comparative values in my case are unevaluated. When switched out for an (eval) the case still doesn't work.

Code: Select all

(setq a 1)
(setq b 2)
(setq c 3)
(setq d 1)

(case d
   ((eval a) (do-this))
   ((eval b) (do-that))
   ((eval c) (do-something))
   (true)
)

=> nil
What don't I understand?
-statik

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

As this example shows, the expression in the exp-N position in each (exp-N body-N) pair is completely unevaluated.

> (set 'a 5)
5
> (set 'test '(eval a))
(eval a)
> (eval test)
5
> (case test (5 'zero) ((eval a) 'one) (pete 'two) (true 'magoo))
one

That is, no attempt is made to evaluate the expression (eval a) in ((eval a) 'one).

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

yes, you have to use constants:

Code: Select all

(case d
   (1 (do-this))
   (2 (do-that))
   (3 (do-something))
   (true)
) 
Lutz

statik
Posts: 58
Joined: Thu Apr 14, 2005 1:12 am

Post by statik »

Is there a work around, or can we impliment a change? Does it work this way for a reason?
-statik

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

statik wrote:Is there a work around, or can we impliment a change? Does it work this way for a reason?
Dmitry has written "ecase":

Code: Select all

(define-macro (ecase _v)
  (eval (append (list 'case _v)
		(map (fn (_i) (set-nth 0 _i (eval (_i 0))))
		     (args)))))
(set 'a 1)
(set 'b 2)

(ecase b
   ((eval a) (println "a is 1")) 
   ((eval b) (println "b is 2")) 
   (true) 
)
http://en.feautec.pp.ru/SiteNews/funlib_lsp

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

'case' is a very fast switcher for the reason that is does not evaluate. For many years actually it was working with evaluation, but then got changed to be more compatible with other LISPs.

Lutz

Fanda
Posts: 253
Joined: Tue Aug 02, 2005 6:40 am
Contact:

Post by Fanda »

Use 'if' if you want to evaluate...

Fanda

Locked