【问题标题】:Basic Prolog Nth Number of Tribonacci Series基本 Prolog 第 N 个 Tribonacci 系列
【发布时间】:2018-08-28 20:02:47
【问题描述】:

在我的编程原理课上,我们开始学习 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 不等于目标 (T),那么 X 应该等于 X+Y+Z 以获得序列中的下一个数字,并且 Count 减 1。不幸的是,除非它在静态条件语句的参数中,否则它会返回 false。这是为什么呢?

【问题讨论】:

  • 我没有深入阅读您的代码,但至少“X is X+Y+Z”部分显然无效。 “is”右侧的所有变量都必须是数字。
  • 和“Count is Count - 1”部分也是如此。当prolog变量绑定一个值时,不回溯就无法更改。
  • 您正在编写 Prolog,就好像它是像 C 这样的语言的音译。这不是一个好主意。 Prolog 非常不同。一方面,您不会像其他语言那样“分配”变量。它们受术语统一的约束。 X is X+Y+Z 将始终失败,除非 X 的值实际上是 X+Y+Z 的值。换句话说,如果Y+Z 加起来为零。
  • 感兴趣的:Tribonacci 数 - OEIS A000073

标签: prolog fibonacci


【解决方案1】:

你的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).

【讨论】:

    猜你喜欢
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2012-07-02
    • 2014-11-04
    • 2019-11-10
    相关资源
    最近更新 更多