在我的编程原理课中,我们开始学习Prolog,我们的任务是创建一个查询trib(N,T),如果T是第N个Tribonacci数,则为真,系列为0,0,1,1 ,2,4,(等......)。我已经写了我认为会回答的答案:
addThis(Count, X, Y, Z, Goal) :-
( Count == 1, Goal == 0 ->
true;
Count == 2, Goal == 0 ->
true;
Count == 3, Z \== Goal ->
false;
Count == 3, Z == Goal ->
true;
Count \== 3, Z \== Goal ->
X is X+Y+Z, Count is Count - 1,
addThis(Count, Y, Z, X, Goal)).
trib(N, T) :- addThis(N, 0, 0, 1, T).
然而,如果N = 1且T = 0则为真,N = 2且T = 0为真,如果N = 3且Z = T则为真,如果N = 3但Z!= T则一定是假的。这是通过最后一个递归if语句完成的,只要Count不是3且Z不等于Goal(T),那么X应该等于X + Y + Z以获得序列中的下一个数字,并且Count减少1.不幸的是,除非它在静态条件语句的参数中,否则返回false。这是为什么?
答案 0 :(得分:0)
您的trib/2
很好,但您必须重写addThis/5
:
% Where X,Y,Z are the three first elements of the Tribonacci sequence:
% Prototype: addThis(N, X, Y, Z, NthElement)
addThis(0, X,_Y,_Z,X). % returns the 0th element
addThis(1,_X, Y,_Z,Y). % returns the 1st element
addThis(2,_X,_Y, Z,Z). % returns the 2nd element
% returns the sum of the three elements
% i.e. the fourth element
addThis(3,X,Y,Z,Next):-
Next is X+Y+Z.
% returns the Nth element recursively
addThis(N,X,Y,Z,Next):-
N > 3,
NewN is N-1,
W is X+Y+Z,
addThis(NewN,Y,Z,W,Next).
trib(N,Goal):-
addThis(N,0,0,1,Goal).