I am trying to write some of my first code in emacs lisp and I can't understand the following behaviour
(defun sq (x) (* x x))
(member 9 '(1 2 3 4 (sq 3)))
This evaluates to nil
but the value I was expecting was (9)
Now I guess* emacs lisp uses applicative-order evaluation, so why was the list not evaluated before the function was applied?
Since I needed it just for testing a non-nil condition, I could finally make it work as follows,
(member 9 (cons (sq 3) '(1 2 3 4)))
which evaluates to (9 1 2 3 4)
My question is does this work because (sq 3)
is a "direct" argument to a function (cons) unlike in the earlier example where it was an element inside an argument ? Is using cons
an acceptable workaround here or is there a better/correct way to get the desired behaviour?
* While couldn't find out for sure what order evaluation emacs lisp uses, I tried the same expression in scheme interpreter and got the same answer and from SICP I know that scheme uses applicative order evaluation. Now I am really really confused!
Any help appreciated.
The problem is that you're quoting the list and therefore none of its elements will be evaluated, but will merely be passed in as literal symbols. If you'd like to evaluate certain elements of the list while passing others in as literals, the most convenient form is to use the backquote, i.e.:
(member 9 `(1 2 3 4 ,(sq 3)))
Backquote behaves identically to normal quote, except that list elements preceded by a comma are evaluated, with the result of the evaluation substituted back into the list.
Alternatively, you could use the list
function, which evaluates its parameters (unless explicitly quoted):
(member 9 (list 1 2 3 4 (sq 3)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With