How to write mod/3 function for successor arithmetic (Peano's Numbers) in prolog?
Think of it this way:
If you want to find the mod of 10 and 4, you divide 10 by 4 and return the reminder. But since divide is multiple subtractions we will use the multiple subtraction logic here.
For Example: 10 mod 4
is same as 10-4 mod 4
which is 6 mod 4
which is again same as 6-4 mod 4
= 2 mod 4
. Since the first element (2) is less than the second (4), we terminate the program here and return first element (2).
mod(_, 0, 0).
Says that anything mod 0 is 0.
mod(0, _ , 0).
Says that 0 mod anything is 0.
mod(X, s(0), 0).
Says that anything mod 1 is 0.
This is the tricky part:
mod(A, B, N) :- minus(A, B, R), (R @< B -> N = R ; mod(R, B, N)).
This uses the multiple minus logic. If first removes second from first and then checks if first is smaller that the second. If yes, recursively call the mod function. If not return the first element.
s(0).
s(X):- X.
plus(0, Y, Y).
plus(s(X), Y, s(Z)):- plus(X , Y , Z).
minus(A, B, C) :- plus(C, B, A).
mod(_, 0, 0).
mod(0, _ , 0).
mod(X, s(0), 0).
mod(A, B, N) :- minus(A, B, R), (R @< B -> N = R ; mod(R, B, N)).
Thank you @Toby for the edit request.