Search code examples
prologsuccessor-arithmetics

Prolog: Recursive Multiplication of 2 Numbers


I don't understand why this recursive definition of a multiplication is working.
I get the add part, but how is the value of "A" in this context. The code is the following:

add(0,X,X).
add(s(X),Y,Z):-add(X,s(Y),Z).

mult(0,X,0).
mult(s(X),Y,Z):-mult(X,Y,A), add(Y,A,Z).

Solution

  • In this context, A is the value of (X-1) * Y. You find this value recursively with the mult rule then add it to Y in the add rule to get your final result. It is writing the multiplication as X * Y = (X - 1) * Y + Y

    Really what ends up happening is it calls add X times, and each of those times it adds Y to the final result (starting from zero). This is exploiting multiplication as repeated addition. Here is a trace by hand:

    1. mult(3, 2, Z)
      Initial call

    2. mult(2, 2, A_1), add(2, A_1, Z)
      Subtract 1 fram X

    3. mult(1, 2, A_2), add(2, A_2, A_1)
      Again.

    4. mult(0, 2, A_3), add(2, A_3, A_2)
      One last time

    5. mult(0, 2, A_3)
      Only one possibility, as zero cannot match s(x). A_3 is set to 0.

    6. mult(0, 2, 0), add(2, 0, A_2)
      Step 4, but with A_3 substituted. We now know that A_2 must be 2.

    7. mult(1, 2, 2), add(2, 2, A_1)
      Step 3, but with A_2 substituted. We now know A_1 must be 4.

    8. mult(2, 2, 4), add(2, 4, Z)
      Step 2, but with A_1 substituted. We now know Z must be 6, the final result.

    For steps 2 through 4 you are counting downward as a way of finding the number of times you need to repeat the addition operation. Step 5 is the base case, starting the final result at zero. In steps 6 through 8 you carry out the addition. This gives the result of Z = 6 = 2 + 2 + 2