Page 1 of 1

How to determine whether a list can be evaluated

Posted: Wed Jul 03, 2019 7:41 am
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?

Re: How to determine whether a list can be evaluated

Posted: Sat Jul 13, 2019 9:08 am
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" !

Re: How to determine whether a list can be evaluated

Posted: Sun May 24, 2020 5:57 pm
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
>