Hi , what is substraction and summation using successors , can any one show me an example for that i know how to do it the normal way .
/* sub(X, Y, Z) ---subtraction */
sub(X, Y, Z) :- add(Y, Z, X).
From stackoverflow
-
First, you need to have a predicate
succ. This is how SWI-Prolog defines it:succ(?Int1, ?Int2) True if Int2 = Int1+ 1 and Int1>=0. At least one of the arguments must be instantiated to a natural number. This predicate raises the domain-error not_less_than_zero if called with a negative integer. E.g. succ(X, 0) fails silently and succ(X, -1) raises a domain-error.Given that, we can define
addlike this:add(0, Y, Y). add(X, Y, Z) :- succ(PredX, X), add(PredX, Y, PredZ), succ(PredZ, Z).And
subtractlike this:subtract(X, 0, X). subtract(X, Y, Z) :- succ(PredY, Y), succ(PredX, X), subtract(PredX, PredY, Z).Note that neither one of these will handle negative numbers (because
succdoesn't), and therefore I haven't bothered to make subtract function whenY > X.
EDIT:
Here's a version of
addandsubtractthat work on any instantiation pattern. I still didn't bother with type-checking (as mentioned by Kaarel in the comments), or negative numbers.add(0, 0, 0). add(0, Y, Y). add(X, 0, X). add(X, Y, Z) :- nonvar(X), succ(PredX, X), (nonvar(Z) -> succ(PredZ, Z), add(PredX, Y, PredZ) ; add(PredX, Y, PredZ), succ(PredZ, Z) ). add(X, Y, Z) :- nonvar(Y), add(Y, X, Z). subtract(0, 0, 0). subtract(X, 0, X). subtract(X, X, 0). subtract(X, Y, Z) :- add(Y, Z, X).Kaarel : Note that the instantiation patterns add(-, +, +) and add(+, -, +) do not work under this definition. Also, you could cut after "add(0, Y, Y)", and check the input type, currently: ?- add(0, blah, R). R = blah ; false.Pesto : Actually, add(+, -, +) does work because succ is never called on Y. However, see my edit.Kaarel : ?- add(2, X, 3). ERROR: succ/2: Arguments are not sufficiently instantiated
0 comments:
Post a Comment