syntaxprologprolog-dif

Prolog return results


For homework, so nothing explicit, please:

Is there a way to get Prolog to return only the first Goal found by the program while ignoring the other Goals that are found?

For illustrative purposes, given the program:

permutation([X|Xs],Zs):-permutation(Xs,Ys), insert(X,Ys,Zs).
permutation([],[]).

Is there a way to make the program only return the first permutation as its only solution? In the following case:

| ?- permutation([1,2,3],X).

X = [1,2,3] ? ;

X = [1,3,2] ? ;

X = [2,1,3] ? ;

X = [2,3,1] ? ;

X = [3,1,2] ? ;

X = [3,2,1] ? ;

no

Can we just have

X = [1,2,3] ?;
no

as the solution?


Solution

  • The cut it's the control you are looking for. Place it where you need to commit to a solution (here on toplevel, I guess). There is also the builtin once/1, that allows to restrict the scope of the commit 'locally' (useful for instance inside a conjunction inlined in a findall/3).