简体   繁体   English

如何编写用于递归减法的 prolog 程序

[英]How to write a prolog program for recursive subtraction

I want a recursive subtraction program in prolog.我想要一个 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..我需要将此程序转换为 prolog 程序..

Although it has no practical use, a more direct translation from the Scheme code to a corresponding Prolog code would be as follows:虽然它没有实际用途,但从 Scheme 代码到相应的 Prolog 代码的更直接转换如下:

% 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.NumberExpression计算的值时,谓词Number is Expression为 True。

Examples:例子:

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

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

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

Prolog works a bit different. Prolog 的工作方式略有不同。 A code example for numbers in successor format (where for example s(0) equals 1 ) would be:后继格式数字的代码示例(例如s(0)等于1 )将是:

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.两种情况:要么第二个属性为 0,要么前两个属性大于零。 Downside is that the case M<N can not be computed.缺点是无法计算M<N的情况。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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