How to determine whether a list can be evaluated

Q&A's, tips, howto's
Post Reply
lyl
Posts: 37
Joined: Sun Mar 25, 2018 5:00 am

How to determine whether a list can be evaluated

Post by lyl »

Code: Select all

(setq a '(1 2 3)) ;; This list can not be evaled
(setq b '(1 a)) ;; This list can be evaled, (eval b) --> (2 3)
(setq c '(+ 1 2)) ;; This list can be evaled, (eval c) --> 3
My quesstion is:
Is there an universal method to determine whether a list can be evaluated or not?

In the following example:

Code: Select all

(setq a '(1 2 3)) 
(setq d '((1 a) (3 4)))
(define (f lst) (+ (last lst) 1))
(f (d 0)) ;;->ERR: value expected : a
          ;;  called from user function (f (d 0))
(f a) ;;-> 4
The error in (f (d 0)) can be corrected by (f (eval (d 0))).
But "eval" can not used like this: (f (eval a)).
As the structure of the argument "lst" can not be forseen, is there a way to determine whether a list can be evaluated or not?

newBert
Posts: 143
Joined: Fri Oct 28, 2005 5:33 pm
Location: France

Re: How to determine whether a list can be evaluated

Post by newBert »

lyl wrote:

Code: Select all

(setq a '(1 2 3)) ;; This list can not be evaled
It's normal, because ‘1’ is neither a primitive nor a lambda

Code: Select all

(setq b '(1 a)) ;; This list can be evaled, (eval b) --> (2 3)
Also normal, because (1 a) is equivalent to (rest a) <- implicit indexing

Code: Select all

(setq c '(+ 1 2)) ;; This list can be evaled, (eval c) --> 3
Normal, because ‘+’ is a primitive
My quesstion is:
Is there an universal method to determine whether a list can be evaluated or not?
Maybe testing wether the first member of the quoted list is a primitive or a lambda ?...

Code: Select all

> (setq a '(1 2 3))
(1 2 3)
> (or (lambda? (eval (first a))) (primitive? (eval (first a))))
nil
> (eval a)
ERR: illegal parameter type in function eval : 2

> (setq b '(1 a))
(1 a)
> (or (lambda? (eval (first b))) (primitive? (eval (first b))))
nil
>(eval b)
(2 3)

> (setq c '(+ 1 2))
(+ 1 2)
> (or (lambda? (eval (first c))) (primitive? (eval (first c))))
true
> (eval c)
3
But it doesn't work for ‘b’, so it's not really "universal" !
BertrandnewLISP v.10.7.6 64-bit on Linux (Peppermint 10)

newBert
Posts: 143
Joined: Fri Oct 28, 2005 5:33 pm
Location: France

Re: How to determine whether a list can be evaluated

Post by newBert »

lyl wrote:My quesstion is:
Is there an universal method to determine whether a list can be evaluated or not?
Oops ! Why didn't I think of catch ?

Code: Select all

> (setq a '(1 2 3))
(1 2 3)
> (catch (eval a) 'result)
nil  ; `a` can't be evaluated (see error below in `result`)
> result
"ERR: illegal parameter type in function eval : 2"

> (setq b '(1 a))
(1 a)
> (catch (eval b) 'result)
true  ; `b` can be evaluated (see `result`)
> result
(2 3)

> (setq c '(+ 1 2))
(+ 1 2)
> (catch (eval c) 'result)
true
> result
3
> 
BertrandnewLISP v.10.7.6 64-bit on Linux (Peppermint 10)

Post Reply