Adding dynamical amount of numbers

51 views Asked by At

Take a given database, e.g.

input(80).
input(30).
input(25).
input(90).

Compute the amount of inputs above 50 times 100, constrained to only taking /1 input. e.g.

%compute(?integer).
compute(I).
I = 200 %seeing as input(80) and input(90) matches the condition of being above 50

I have tried the following prolog code to mimick the compute function, unsuccessfully:

compute(I) :- input(G), G>50, I is I+100.

The I+100 does not work as I intend.

1

There are 1 answers

0
Eugene Sh. On BEST ANSWER

Prolog is searching the matches one by one, and returning query result for EACH input, not for all of them. To collect all of the matching values, you can use bagof, setof or findall metapredicates. Here is the code that is doing what you have defined:

input(80).
input(30).
input(25).
input(90).

compute(I) :- 
    findall(X, (input(X), X>50), L), % Find all X's that are 'input' and >50 into L
    length(L,Len),                  % Find the length of L and put into Len
    I is Len * 100.                 % I is Len times 100