Take the 2-minute tour ×

I am very new to prolog and am having some issues understanding some basic arithmetic. I want to create a functor that will recursively multiply. IE: 3*4 = 3+3+3+3 = 12.

I put it through SWIPL's trace command and it fails when decrementing Count.

Here is the code I have so far but it does not work.

multn(_, Count ,Return) :- Count is Count-1,
                           Return is 0, 
                           Return is Return + _.

EDIT: made some new changes based on what you said about the functionality of "is".

multn(_, Count ,Return) :- Count1 is (Count-1), 
                           Return is (Return1 + _).

Now it is making it all the way down the recursion chain to the base case and when it starts it way back up it fails out trying to todo Return is (Return1+ _). It seems to be changing the _ variable. here it my trace:

[trace]  ?- multn(3,2,X).
   Call:  (6) multn(3, 2, _G388) ? creep
^  Call:  (7) _L142 is 2+ -1 ? creep
^  Exit:  (7) 1 is 2+ -1 ? creep
   Call:  (7) multn(_L160, 1, _L143) ? creep
^  Call:  (8) _L163 is 1+ -1 ? creep
^  Exit:  (8) 0 is 1+ -1 ? creep
   Call:  (8) multn(_L181, 0, _L164) ? creep
   Exit:  (8) multn(_L181, 0, 0) ? creep
^  Call:  (8) _L143 is 0+_G461 ? creep
ERROR: is/2: Arguments are not sufficiently instantiated
^  Exception: (8) _L143 is 0+_G461 ? creep
   Exception: (7) multn(_L160, 1, _L143) ? creep
   Exception: (6) multn(3, 2, _G388) ? creep

Last EDIT: Finally figured it out, using _ was causing the weird change in value. Thanks for your help.

share|improve this question
yeah, all _s are different, even if inside one rule. You should name your variables - variables with same name are the same variable. All Xs in X*(N+1)=X*N+X must be the same. –  Will Ness Apr 28 '13 at 9:23
add comment

1 Answer

It looks like your don't understand how Prolog works.

The key thing to understand is that both Count in Count is Count-1 are the same, they must have the same value. It's like variables in algebra - all Xs in an equation means the same value. So Count is Count-1 will always fail.

Similar problems with Return variable.

In Prolog you have to introduce new variables to do what you intended, like NewCount is Count-1.

share|improve this answer
add comment

Your Answer


