1

i'm studying prolog and I have to creat a program that returns the addition of numbers (in a list), that are smaller than a given number. I have this..

additionsmaller([X|XS],K,R):-X>K, additionsmaller(XS,K,R).
additionsmaller([X|XS],K,R):-X<K, additionsmaller(XS,K,T), R is T + X.
additionsmaller([X],K,X):-X<K.
additionsmaller([X],K,0):-K<X.

I expect for example:

additionsmaller([1,2,3,4,2],4,R).
R=8

But it give me false.

I'm using this https://swish.swi-prolog.org

What can I do to fix this? what is wrong with my code?

1 Answers1

0

The problem cames from the fact that, for a value V you handle only the cases X<V and X>V not the case X=V. In fact, if you replace X>K with X>=K, your program will give the result R=8.

Let me say two things about your program:

First of all, you don't need the last two lines in your code (i.e. additionsmaller([X],K,X):-X<K. and additionsmaller([X],K,0):-K<X.). Just replace these two lines with additionsmaller([],_,0).

Second: you should consider also to write a tail recursive solution, like this:

additionSmallerTail([],_,V,V).
additionSmallerTail([H|T],K,V,V0):-
    H >= K,
    additionSmallerTail(T,K,V,V0).
additionSmallerTail([H|T],K,V,V0):-
    H < K,
    V1 is V+H, 
    additionSmallerTail(T,K,V1,V0).

?- additionSmallerTail([1,2,3,4,2],4,0,R).
R = 8
false

Why using tail recursion? This link is interesting.

damianodamiano
  • 2,528
  • 2
  • 13
  • 21