prologlogic-programmingprolog-setof

Prolog: Failure driven loops


I used the following failure driven loop to list everything without using semicolons.

happiness(fred,5).
happiness(john,3).
happiness(grace,2).

someGoal(X) :-
        happiness(X,Y), write(Y), tab(4), fail.

In query mode, I get this as expected

?- someGoal(_).
5    3    2 

How can I insert these numbers into a list rather than writing them to screen? I could not handle this within someGoal since backtracking seems implicit.


Solution

  • You are right, backtracking it's the way Prolog handles alternatives.

    Use findall/3, that collect all alternatives using backtracking 'internally':

    someGoal(X, Values) :-
        findall(Value, happiness(X, Value), Values).
    

    Then ?- someGoal(_, Values). will instance Values = [5, 3, 2]