title: Multiplying peano integers in swi-prolog
body: <p>I am currently on the verge of getting mad trying to solve a simple "multiply peano integers" problem in Prolog.</p>
  
  <h2>Basic rules</h2>
  
  <ul>
  <li>A peano integer is defined as follows: 0 -> 0; 1 -> s(0); 2 -> s(s(0)) s(s(s(0) -> 3 etc.</li>
  <li>The relation is to be defined as follows: multiply(N1,N2,R)
  <ul>
  <li>Where
  <ul>
  <li>N1 is the first peano integer (i.e. something like s(s(0)))</li>
  <li>N2 is the second peano integer (i.e. something like s(s(0)))</li>
  <li>R is the resulting new peano integer (like s(s(s(s(0))))</li>
  </ul></li>
  </ul></li>
  </ul>
  
  <p>I am aware of the fact that Prolog provides basic arithmetic logic by default, but I am trying to implement basic arithmetic logic using peano integers.</p>
  
  <p>As a multiplication is basically a repeated addition, I think it could look something like this:</p>
  
  <h2>Prolog attempts</h2>
  
  <pre><code>%Addition
  % Adds two peano integers 3+2: add(s(s(s(0))),s(s(0)),X). --&gt; X = s(s(s(s(s(0)))))
  add(X,0,X).
  add(X,s(Y),s(Z)) :- add(X,Y,Z).
  
  %Loop
  %Loop by N
  loop(0).
  loop(N) :- N&gt;0, NewN is N-1, loop(NewN).
  </code></pre>
  
  <p>The problem is that I am out of ideas how I can get prolog to run the loop N times based on the coefficient, adding the peano integers and building up the correct result. I'm confident that this is rather easy to achieve and that the resulting code probably won't be longer than a few lines of code. I've been trying to achieve this for hours now and it's starting to make me mad.</p>
  
  <p>Thank you so much for your help, and ... Merry Christmas!</p>
  
  <p>Mike</p>