简体   繁体   English

prolog 一元数 - 评估表达式

[英]prolog unary numbers - evaluating expression

I am trying to understand Prolog and I came up to following situation.我试图了解 Prolog 并且我遇到了以下情况。 I have defined natural numbers (unary) in following way:我以下列方式定义了自然数(一元):

n(0).
n(s(X)) :- nat(X).

Which means that 0 is 0, s(0) is 1, s(s(0)) is 2 etc...这意味着 0 是 0,s(0) 是 1,s(s(0)) 是 2 等等......

Then I defined predicate add:然后我定义谓词添加:

add(0, Y, Y) :- nat(Y).
add(s(X), Y, s(Z)) :-
   add(X, Y, Z).

Which adds two unary numbers and result stores to Z.它将两个一元数和结果存储添加到 Z。

Now I have following predicate "test" what demonstrates my problem:现在我有以下谓词“测试”证明了我的问题:

test(s(0),0).

Then in interpret I type:然后在解释中输入:

add(s(0),0,R). %result: R = s(0), which is correct

Then i try:然后我尝试:

test(add(s(0),0,R), 0).

So the first argument should result in R = s(0), second argument is zero, so the whole expression should be evaluated as true, but prolog says false.所以第一个参数应该导致 R = s(0),第二个参数为零,所以整个表达式应该被评估为 true,但 prolog 说 false。 I guess that it has something to do with the point, that the add(s(0),0,R) inside the "test" predicate does not evaluate the way I think.我想这与这一点有关,即“测试”谓词中的 add(s(0),0,R) 不会评估我的想法。 Could anyone please explain this to me or eventually provide some link that describes this behaviour?谁能向我解释一下,或者最终提供一些描述这种行为的链接? Thanks for any help.谢谢你的帮助。 Cheers.干杯。

No, prolog does not work the way you assume it to.不,prolog 不像您想象的那样工作。 When you ask当你问

?- test(add(s(0),0,R), 0).

prolog tries to find a matching clause. prolog 尝试查找匹配子句。 However, there is no matching clause in your database, since s(0) does not match add(s(0),0,R) .但是,您的数据库中没有匹配的子句,因为s(0)不匹配add(s(0),0,R) Two structures can only match if the have the same functor.两个结构只有在具有相同函子时才能匹配。

s(0) has the functor s while add(s(0),0,R) has the functor add . s(0)具有函子sadd(s(0),0,R)具有函子add

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

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