Evaluation order in emacs lisp

I am trying to write some of my first code in emacs lisp and I cannot understand the following behavior

(defun sq (x) (* xx)) (member 9 '(1 2 3 4 (sq 3))) 

This evaluates to nil , but the expected value I was (9)

Now I assume that * emacs lisp uses an applicative order estimate, so why wasn't the list evaluated before the function was applied?

Since I needed it only to test a condition other than zero, I could finally do it like this,

 (member 9 (cons (sq 3) '(1 2 3 4))) 

which is rated as (9 1 2 3 4)

My question is that this works because (sq 3) is the "direct" argument of the function (cons), unlike the previous example, where was it the element inside the argument? Does cons an acceptable workaround here, or is there a better / correct way to get the desired behavior?

* While it was not possible to know exactly what the emacs lisp score evaluates to, I tried the same expression in the schema interpreter and got the same answer, and from SICP I know that the schema uses the applicative order estimate. Now I am really very confused!

Any help was appreciated.

+7
source share
1 answer

The problem is that you are quoting a list, and therefore, none of its elements will be evaluated, but will simply be passed as literals. If you want to evaluate some list items when passing others as literals, the most convenient form is to use backquote, i.e.:

 (member 9 `(1 2 3 4 ,(sq 3))) 

Backquote behaves the same as a regular quote, except that list items preceding a comma are evaluated and the result of the evaluation is replaced back to the list.

Alternatively, you can use the list function, which evaluates its parameters (unless explicitly specified):

 (member 9 (list 1 2 3 4 (sq 3))) 
+16
source

All Articles