Search code examples
schemelispelispsicp

a-plus-abs-b: Invalid function: (if (> b 0) + -)


I am doing Exercise 1.4 of SICP

Exercise 1.4. Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:

#+begin_src emacs-lisp :session sicp :lexical t
(defun a-plus-abs-b(a b)
  ((if (> b 0) + -) a b))
(a-plus-abs-b 9 4)

#+end_src

Run and got the error

a-plus-abs-b: Invalid function: (if (> b 0) + -)

What's the problem?


Solution

  • In Emacs Lisp you need to do it like this:

    (defun a-plus-abs-b (a b)
      (funcall (if (> b 0) '+ '-) a b))
    

    That's because Emacs Lisp is a Lisp-2.