Reputation: 2190
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
Upvotes: 1
Views: 63
Reputation: 2436
"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
Upvotes: 0