Recursive multiplication in prolog

2019-04-13 21:45发布

问题:

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!