简体   繁体   中英

How to write a prolog program for recursive subtraction

I want a recursive subtraction program in prolog.

the scheme of the program is

(define (sub m n)
(cond
    ((= n 0) m)
    (else (sub (- m 1) (- n 1)))))

I need to convert this program into a prolog program..

Although it has no practical use, a more direct translation from the Scheme code to a corresponding Prolog code would be as follows:

% mode: sub(+, +, -)

sub(A, B, C) :-
    (   B = 0               % if
    ->  C = A               % then
    ;   A1 is A-1,          % else
        B1 is B-1,
        sub(A1, B1, C) ).

The predicate Number is Expression is True when Number is the value to which Expression evaluates.

Examples:

?- sub(12, 7, C).
C = 5.

?- sub(7, 12, C).
C = -5.

?- sub(7, 7, C).
C = 0.

Prolog works a bit different. A code example for numbers in successor format (where for example s(0) equals 1 ) would be:

sub(M,0,M).
sub(s(M),s(N),R):-
    sub(M,N,R).

Test:

?- sub(s(s(s(0))),s(0),R).
R = s(s(0)) ;
false.

This is the easiest solution. Two cases: either the second attribute is 0 or the first two attributes are greater than zero. Downside is that the case M<N can not be computed. Please note that capital letters are variables and that the code works from top to botton, from left to right.

Working with numbers in the normal decimal format is more complex since mathematical terms need to be calculated explicitly. Example:

?- M = 4, N = M-1.
M = 4,
N = 4-1.

?- M = 4, N is M-1.
M = 4,
N = 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM