5
votes

I am learning programming in Prolog and have a problem with a rule, it must search for the solution and once it is found, it must to do "nothing". But it have failed and given me more than one solution. I tried to do something like this:

% here the solution is already found and there's nothing to be done.
findsolution:-
       solution(X).

% trying to find the solution and use assert/1 if it was found. 
 findsolution:-
        do_something, 
        do_whatever, 
        assert(solution(X)).

If the solution was not found, the first rule fails and the backtracking will try the second implementation of the rule . If the second find the solution, the first rule must succeed, the backtracking is not necessary anymore when I call 'findsolution/0' again only the first rule will be queried. My intent is to be efficient, preventing unnecessary queries, because I know there only one solution, just don't know what. I'm grateful.

P.S. the context of my program is not the same here, it is to simplify. Sorry for my bad English.

1

1 Answers

7
votes

If you want to stop the search, then what you must do is avoid (controlling) backtracking using the cut predicate, check the docs.
In this case what you need to do basically is to avoid backtracking in your first clause, using this cut (!) predicate:

findsolution:- solution(X), !.