Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

function - 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..

question from:https://stackoverflow.com/questions/65874036/how-to-write-a-prolog-program-for-recursive-subtraction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...