-1

I was just solving the book Structure and Interpretation of Computer Programs and have a question concerning exercise 1.10, which, using Ackermann's function defined as

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

determine the value of the expression (A 1 10).

Here's my solution:

(A 1 10)
(A 0 (A 0 9))
(A 0 (18))
36

Now i know the answer is 1024, i got the solution on the internet but what I thought would happen is when x's value would decrement the value of x in (A x (- y 1)) would be the decremented value but it seems it isn't the case. How ? Wouldn't as per the applicative-order it would be true? Moreover it was the same thing that happened in ex 1.9 when the decremented value was able to call the function. Thank you in advance.

  • What language is this? – Mark Rotteveel Aug 12 '18 at 06:44
  • Mark it's scheme, a dialect of lisp – King Kapoor Aug 12 '18 at 06:51
  • `(- x 1)` does not alter `x` so it's `1` the whole duration of the first call. Evaluation of arguments is done before apply but does not mutate variables unless you use mutation. Why get the solution from the internet?don't have scheme installed? – Sylwester Aug 12 '18 at 06:54
  • Yes i have scheme and i got the solution(1024) but it wasn't matching up with my wrong answer (36) so i went to the internet. I am sorry but would you mind explaining that mutate variable thing? – King Kapoor Aug 12 '18 at 07:08
  • (A 1 10) --> {x=1; y=10} (A (- x 1) (A x (- y 1))). Calculating `(- x 1)` doesn't change the value of `x` itself. It remains what it is, `x=1`. --> (A (- 1 1) (A 1 (- 10 1))) --> (A 0 (A 1 9)). – Will Ness Aug 12 '18 at 17:34

1 Answers1

1

The value of x doesn't change - no variable's value changes until mutation is introduced about halfway through the book.
Use the substitution method as the book teaches.

It goes

(A 1 10)
[Replace x with 1, y with 10 in (A (- x 1) (A x (- y 1)))]
(A (- 1 1) (A 1 (- 10 1))) 
(A 0 (A 1 9))      
(* 2 (A 1 9))
[Replace x with 1, y with 9]
(* 2 (A (- 1 1) (A 1 (- 9 1)))))
(* 2 (A 0 (A 1 8))))
(* 2 (* 2 (A 1 8)))
[...]
(* 2 (* 2 (A 0 (A 1 7))))
[...]

(At which point you might realise that (A 1 K) is the K:th power of 2, or you might not.)

molbdnilo
  • 64,751
  • 3
  • 43
  • 82