Prolog中偶数和奇数的两种实现的区别 [英] Difference between two Implementation of even and odd in Prolog
问题描述
我有两个 Prolog 实现,功能是判断给定的数是奇数还是偶数
i have two implementation of Prolog , the Function is to decide if the given number is odd or even
第一个正常工作
even1(0).
even1(X) :- X>0 ,X1 is X-1, odd1(X1).
odd1(1).
odd1(X) :- X>1 , X1 is X-1, even1(X1).
even1(2) 返回真
even1(2) returns true
但是第二个不能正常工作
but the second one doesnt work correctly
even2(0).
even2(X) :- X>0 , odd2(X-1).
odd2(1).
odd2(X) :- X>1 , even2(X-1).
even2(2) 返回 false谁能向我解释一下这两者之间的区别是什么?
even2(2) returns false can anyone explain to me whats is the difference between the two of them ?
推荐答案
Prolog 是一种关系语言,而不是一种功能语言.因此,当您调用 odd2(X-1)
时,谓词参数 X-1
不会被评估为表达式,而是被解释为复合词:
Prolog is a relational language, not a functional language. Thus, when you call odd2(X-1)
, the predicate argument, X-1
, is not evaluated as an expression but interpreted as a compound term:
?- functor(X-1, Name, Arity).
Name = (-),
Arity = 2.
您可以使用系统跟踪功能检查 Prolog 证明查询时会发生什么:
You can check what happens when Prolog proves a query by using your system trace functionality:
?- trace.
true.
[trace] ?- even2(2).
Call: (8) even2(2) ? creep
Call: (9) 2>0 ? creep
Exit: (9) 2>0 ? creep
Call: (9) odd2(2-1) ? creep
Call: (10) 2-1>0 ? creep
Exit: (10) 2-1>0 ? creep
Call: (10) even2(2-1-1) ? creep
Call: (11) 2-1-1>0 ? creep
Fail: (11) 2-1-1>0 ? creep
Fail: (10) even2(2-1-1) ? creep
Fail: (9) odd2(2-1) ? creep
Fail: (8) even2(2) ? creep
false.
请注意,表达式 2-1-1
的计算结果为零,但作为复合词,调用 even2(2-1-1)
不统一使用谓词的基本情况,even2(0)
:
Note that the expression 2-1-1
evaluates to zero but, being a compound term, the call even2(2-1-1)
doesn't unify with your base case for the predicate, even2(0)
:
?- even2(2-1-1) = even2(0).
false.
?- 2-1-1 = 0.
false.
因此,Prolog 尝试第二个子句,并且调用最终未能通过 X>0
检查.请注意,>/2
作为算术比较谓词,它确实在实际比较之前评估其参数.
Therefore, Prolog tries the second clause and the call eventually fails the X>0
check. Note that >/2
, by being an arithmetic comparison predicate, it does evaluate its arguments prior to the actual comparison.
这篇关于Prolog中偶数和奇数的两种实现的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!