Search code examples
elisp

Elisp to define a Ackermann's function


I am reading SICP and refer to its
Exercise 1.10. The following procedure computes a mathematical function called Ackermann's function.

(define (A x y)
  (cond ((= y 0) 0)
        ((= x 0) (* 2 y))
        ((= y 1) 2)
        (else (A (- x 1)
                 (A x (- y 1))))))

Rewrite it with elisp

(defun A (x y)
  (cond ((= y 0) 0)
        ((= x 0) (* 2 y))
        ((= y 1) 2)
        (else (A (- x 1)
                 (A x (- y 1))))))

(A 1 10)

Report error:
A: Symbol’s value as variable is void: else

Refer to elisp's control structure thus lost in various alternatives.

Could you please provide hints to define that function with cond and else


Solution

  • In Emacs Lisp you use t instead of else. In cases like this, Language Reference is a good place to begin research... https://www.gnu.org/software/emacs/manual/html_node/elisp/Conditionals.html:

    Often we want to execute the last clause whenever none of the previous clauses was successful. To do this, we use t as the condition of the last clause, like this: (t body-forms). The form t evaluates to t, which is never nil, so this clause never fails, provided the cond gets to it at all. For example:

    (setq a 5)
    (cond ((eq a 'hack) 'foo)
          (t "default"))
    ⇒ "default"