1

here is the addition code for two input( like we want the result in Z if X+1 plus Y have Z+1 for a result).

    natural_number(0).
    natural_number(s(X)) :- natural_number(X).

    pl(0,X,X) :- natural_number(X).
    pl(s(X),Y,s(Z)) :- pl(X,Y,Z).

But I wonder that can we use the similar code for 3 components like

    pl(s(0),s(s(0)),s(s(s(0))),W) 
    and got a result W = s(s(s(s(s(s(0))))))

Thank you in advance.

user6893697
  • 21
  • 1
  • 2
  • Add the first to the second and then the result to the third? –  Sep 28 '16 at 12:43
  • 1
    See [this answer](http://stackoverflow.com/a/10141181/772868) for a general approach to reason about termination. – false Sep 28 '16 at 19:41

1 Answers1

1
pl(A, B, C, Sum) :-
    pl(A, B, Tmp),
    pl(Tmp, C, Sum).

Or, if you want to add a list of natural numbers, you can of course do a fold over it:

pl([], 0).
pl([N|Ns], Sum) :-
    foldl(pl, Ns, N, Sum).

or even (after the suggestion by CapelliC):

pl(Ns, Sum) :- foldl(pl, Ns, 0, Sum).

PS: It is not always a bad idea to use successor notation. At least one valid use of it is to use it to keep track of the length of a queue, as shown in this answer.

Community
  • 1
  • 1
  • 2
    better if shorter ? `pl(Ns, Sum) :- foldl(pl, Ns, 0, Sum).` – CapelliC Sep 28 '16 at 12:54
  • 1
    `pl/4` has very poor termination: [`pl(A,B,C,D)terminates_if b(A),b(B),b(C);b(A),b(B),b(D).`](http://www.complang.tuwien.ac.at/cti/cgi/cti?texta=natural_number%280%29.%0D%0Anatural_number%28s%28X%29%29+%3A-+natural_number%28X%29.%0D%0A%0D%0Apl%280%2CX%2CX%29+%3A-+natural_number%28X%29.%0D%0Apl%28s%28X%29%2CY%2Cs%28Z%29%29+%3A-+pl%28X%2CY%2CZ%29.%0D%0A%0D%0Apl%28A%2C+B%2C+C%2C+Sum%29+%3A-%0D%0A++++pl%28A%2C+B%2C+Tmp%29%2C%0D%0A++++pl%28Tmp%2C+C%2C+Sum%29.) – false Sep 28 '16 at 19:39
  • @false the termination of successor notation arithmetic has been discussed in _many_ question and answers here on SO. –  Sep 29 '16 at 05:48
  • @false PS: As I wrote in my answer, I guess there are some valid uses of successor notation natural numbers in actual programs, but on its own, it is a quite silly way of doing arithmetic :-/ I guess I was too lazy in my answer (and the votes nicely reflect that). –  Sep 29 '16 at 05:51
  • @Boris: This particular definition has never been discussed w.r.t. termination. – false Sep 29 '16 at 10:36