序言中的递归乘法 [英] Recursive multiplication in prolog
问题描述
序言的新手.
使用 swi-prolog
我想递归地做乘法在序言中已经做的事情,而不实际使用乘法.
我想实现它的算法看起来像:
multn(N1, N2, output){if (n2 <=0) 返回输出;别的multn(N1, (N2-1), 输出 + N1)}
例如:4*4 = 4+4+4+4 = 16
edit*:只为这个算法传递正数.
我的知识数据库看起来像:
multn(Num1, 0, Result) :- 结果为 0.multn(Num1, Num2, 结果) :-NewNum2 = Num2 - 1,multn(Num1, NewNum2, NewResult),结果是 Num1 + NewResult.
但是,当我打电话时:
?- multn(2,2,R).
它一直持续下去,为什么这不停止在上述基本情况?
非常感谢您的帮助.
对于整数运算,使用 clpfd 约束.所有严肃的 Prolog 系统都提供它们.例如,对于 SICStus Prolog,将 :- use_module(library(clpfd))
放在您的初始化文件中,以使 CLP(FD) 约束在您的所有程序中可用.
使用 CLP(FD) 约束和一些小的修改,你的初始程序变成:
<前>int_int_prod(_, 0, 0).int_int_prod(Num1, Num2, 结果) :-NewNum2 #= Num2 - 1,int_int_prod(Num1, NewNum2, NewResult),结果#= Num1 + NewResult.现在的重点是:您显然是指您的条款是相互排他性的.
插入 Num2 #>0
在合适的地方这样做!
New to prolog.
edit: using swi-prolog
I want to recursively do what the multiplication method already does in prolog without actually using the multiplication method.
The algorithm I want to implement it looks something like:
multn(N1, N2, output){
if (n2 <=0) return output;
else
multn(N1, (N2-1), output + N1)
}
Ex: 4*4 = 4+4+4+4 = 16
edit*: only passing in positive numbers for this algo.
my knowledge db looks like:
multn(Num1, 0, Result) :- Result is 0.
multn(Num1, Num2, Result) :-
NewNum2 = Num2 - 1,
multn(Num1, NewNum2, NewResult),
Result is Num1 + NewResult.
However, when I call:
?- multn(2,2,R).
It goes on forever, why is this not stopping at the above base case?
Help is much appreciated.
For integer arithmetic, use clpfd constraints. All serious Prolog systems provide them. For example, for SICStus Prolog, put :- use_module(library(clpfd))
in your initialisation file to make CLP(FD) constraints available in all your programs.
Using CLP(FD) constraints and some small modifications, your initial program becomes:
int_int_prod(_, 0, 0). int_int_prod(Num1, Num2, Result) :- NewNum2 #= Num2 - 1, int_int_prod(Num1, NewNum2, NewResult), Result #= Num1 + NewResult.
And now the point: You obviously meant your clauses to be mutually exclusive.
Insert Num2 #> 0
at an appropriate place to do that!
这篇关于序言中的递归乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!