1

I'm trying to write a plus expression for Prolog.

Using an example from the Art of Prolog:

nat(0).
nat(N) :- N > 0, M is N - 1, nat(M).
plus(X, 0, X) :- nat(X).
plus(X, s(Y), s(Z)) :- plus(X, Y, Z).

Then I query:

| ?- plus(1, 1, Y).

no

Why is this not Y = 2?

I tried the example here in this post as follows with similar results:

peano_add(0, Sum, Sum).
peano_add(s(N), M, s(Sum)) :- peano_add(M, N, Sum).

| ?- peano_add(1, 1, Y).

no

enter image description here

false
  • 10,264
  • 13
  • 101
  • 209
notaorb
  • 1,944
  • 1
  • 8
  • 18
  • 1
    For Peano addition: https://stackoverflow.com/a/74939598/ – brebs Aug 02 '23 at 23:02
  • @brebs I tried that example marked as the answer and still have problems with 1 + 1 as updated in the post. – notaorb Aug 03 '23 at 00:25
  • 1
    You are mixing up Peano and numbers as if they are the same. To convert between them: https://stackoverflow.com/a/75645668/ – brebs Aug 03 '23 at 07:41

1 Answers1

0

"1" is not 1, it is the successor of 0. Also, now the other answer is confusing this additionally since "natural" is supposed to be defined like this (isn't it like that in the book??):

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

So with this and plus/3, as defined in your example,

plus(0, X, X) :- natural(X).
plus(s(X), Y, s(Z)) :- plus(X, Y, Z).

if you wanted to add 1 and 1, since 1 is the successor of 0, you'd have to write:

?- plus(s(0), s(0), X).

And this should answer X = s(s(0)), since one plus one is two. You can also subtract with this predicate. Here is the whole thing on GNU-Prolog:

$ gprolog
GNU Prolog 1.4.5 (64 bits)
Compiled Dec 21 2020, 08:56:50 with gcc
By Daniel Diaz
Copyright (C) 1999-2020 Daniel Diaz
| ?- [user]. % define predicates
compiling user for byte code...
natural(0).
natural(s(X)) :- natural(X).
plus(0, X, X) :- natural(X).
plus(s(X), Y, s(Z)) :- plus(X, Y, Z).
end_of_file.
user compiled, 5 lines read - 673 bytes written, 17939 ms

(1 ms) yes
| ?- plus(s(0), s(0), X). % add 1 + 1

X = s(s(0))

yes
| ?- plus(s(0), X, s(s(s(s(0))))). % subtract 4 - 1

X = s(s(s(0)))

yes
TA_intern
  • 2,222
  • 4
  • 12