Prolog:减少参数中的变量 [英] Prolog: Decrementing variable in argument
问题描述
我是Prolog的新手,他被赋予Fibonnaci谓词fib(N,F)的任务,其中N是顺序中的数字,F是值.我想出的办法行不通,但是我找到的解决方案似乎与我完全相同……我无法理解其中的区别.
I am new to Prolog and was tasked with a Fibonnaci predicate fib( N, F) where N is the number in sequence, and F is the value. What I came up with does not work, but the solution I found seems identical to me... I cannot understand the difference.
我的版本:
/* MY VERSION, DOES NOT WORK */
fib( 0, 0).
fib( 1, 1).
fib(N,F) :-
N > 1,
fib(N-1,F1),
fib(N-2,F2),
plus(F1,F2,F).
工作版本:
/* FOUND SOLUTION, DOES WORK */
fib( 0, 0).
fib( 1, 1).
fib(N,F) :-
N > 1,
N1 is N-1,
N2 is N-2,
fib(N1,F1),
fib(N2,F2),
plus(F1,F2,F).
很明显,问题与我有关,使用"N-1"和"N-2"作为参数,而不是先将这些值分配给新变量.但是我不明白...因为在其他递归Prolog代码中,我已经成功地做到了这一点(在参数插槽中减少了一个变量).这有道理吗?
Obviously the problem has something to do with me using "N-1" and "N-2" as arguments rather than assigning those values to new variables first. But I don't get it... because in other recursive Prolog codes, I have successfully done just that (decremented a variable right in the argument slot). Does this make sense?
谢谢!
下面是一个例子,其中"N-1"确实起作用.
Below is an example where the "N-1" did work.
line( N, _, _) :-
N =:= 0.
line( N, M, Char) :-
N > 0,
N mod M =\= 1,
write( Char), write( ' '),
line( N-1, M, Char).
line( N, M, Char) :-
N > 0,
N mod M =:= 1,
write( Char), write( '\n'),
line( N-1, M, Char).
square( N, Char) :-
N > 0,
line( N*N, N, Char).
fib/2的新版本也可以使用!
A new version of fib/2 which also works!
/* NEW VERSION, CHANGED TRIVIAL CASES TO EVALUATE N */
fib( N, 0) :-
N =:= 0.
fib( N, 1).
N =:= 1.
fib(N,F) :-
N > 1,
fib(N-1,F1),
fib(N-2,F2),
plus(F1,F2,F).
推荐答案
序言中,
1 - 2
实际上不执行任何算术运算(我知道,对吗?),它会创建一个结构:
Doesn't actually do any arithmetic (I know, right?), it creates a structure:
-(1, 2)
is
是一个评估该结构的谓词:
And is
is a predicate that evaluates that structure:
is(X, -(1, 2))
将X与 -1
统一.
Also apparently <
and >
(and those like it) are like is
in that they evaluate expressions.
所以这意味着您的 fib
谓词与您的 line
谓词之间的区别是
So that means that the difference between your fib
predicate and your line
predicate is that
fib(0, 0).
使用统一,即测试术语本身是否相等:
is using unification, ie, testing whether the terms themselves are equal:
foo(0).
?- foo(1 - 1).
false
而像 =:=
这样的测试则用于数值相等性测试:
Whereas a test like =:=
tests for numerical equality:
foo(X) :- X =:= 0.
?- foo(1 - 1).
yes
这篇关于Prolog:减少参数中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!