Recursive multiplication in prolog

自古美人都是妖i 提交于 2019-12-06 09:13:20

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/37017320/recursive-multiplication-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!