Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

list - Arithmetic in Prolog - Multiples of a number

I want to create a function multiples(X, N, R) where R is a list containing all multiples of X from X to X * N.

An example would be: multiples(3, 4, [12, 9, 6, 3]), which should give out true.

My code so far:

multiples(X, N, R) :- X >= 1, N >= 1, Z is X*N, contains(Z, R).

contains(Z, [Z|_]).
contains(Z, [W|V]) :- contains(Z,V), L is Z-X, L >= X, contains(L, V).

The output of the console for multiples(3,4,X). is X = [12|_xxxx] and when I type ; an error occurs.
How do I manage to receive the list that I want?
(Maybe my idea is completely wrong).

question from:https://stackoverflow.com/questions/66053210/arithmetic-in-prolog-multiples-of-a-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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].

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...