1

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?

Óscar López
  • 232,561
  • 37
  • 312
  • 386
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

2

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 2
    Yet another little difference between Scheme and Emacs Lisp, and a reason why it's simpler to use Scheme when going through SICP ... but we already discussed that :) – Óscar López Dec 03 '19 at 12:57
  • [TXR Lisp](https://nongnu.org/txr) is a Lisp-2 like Common LIsp and Emacs Lisp; yet you can do this: `(defun plus-abs (a b) [[if (plusp b) + -] a b]))`. The `[...]` notation stands for a special operator `(dwim ...)` which provides Lisp-1 style treatment of symbolic arguments, and strict functional application (it only invokes functions, not operators or macros). Furthermore there exists not only an `if` operator, but also an `if` function which the foregoing `defun` is relying on. – Kaz Dec 03 '19 at 18:50