I found 4 issues with your code. Here is the fixed code, explanation below:
multiples(X, N, R) :-
X >= 1,
N >= 1,
Z is X*N,
contains(X, Z, R).
contains(X, Z, [Z|V]) :-
L is Z-X,
L >= X,
contains(X, L, V).
contains(_, Z, [Z]).
?- multiples(3,4,X).
X = [12, 9, 6, 3] ;
X = [12, 9, 6] ;
X = [12, 9] ;
X = [12] ;
false.
At first in your contains
predicate you access X
and W
and never state their values. Solve X
by adding another attribute to the predicate. Solve W
by replacing it with Z
.
Another problem is the order of your rules. The larger contains
rule should be the "main" rule, only if this one fails the other one should "fire". By placing the default rule on top you get the right result.
Also the rule contains(_, Z, [Z]).
marks the end, therefore it the return list has only the element Z
in it and does not contain any other (unknown) elements.
The last point is that you don't need two contains
calls in the main contains
rule.
The example works for the first answer. However you can improve this with a cut (!
), which prevents going to the second rule after successfully visiting the first rule:
contains(X, Z, [Z|V]) :-
L is Z-X,
L >= X,
!,
contains(X, L, V).
contains(_, Z, [Z]).
?- multiples(3,4,X).
X = [12, 9, 6, 3].