Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

prolog - Gathering all solutions without findall

So as part of my work my code needs to print all the solutions to a query but without using the findall/3 predicate. I've done some reading around and there are ways involving adding the solutions to a list and so on. I tried doing this myself but to with no success; hence I was hoping someone may be able to show how I would print all the solutions without using findall.

The program code is as follows:

    solutions(Q, 100):-
        Q = [X, Y, S],
        between(2,50,X),
        between(2,50,Y),
        S is X+Y,
        Y > X,
        S =< 50.

The Q and the 100 are there because it's needed for another part of the program so ignore that for now. When I query using ?- solutions(Q, 100) I get the results [2,3,5], [2,4,6], [2,5,7] and so on but obviously I need to press ; to get each new result. I need all these to be displayed without the need to press ; and without using findall.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use a failure-driven loop. Try:

?- solutions(Q, 100), write(Q), nl, fail.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...