Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - Find the first solution and stop searching

Tags:

prolog

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.

like image 734
Christopher Avatar asked Mar 27 '15 00:03

Christopher


People also ask

How do you end a program in Prolog?

If you want to exit SWI-Prolog, issue the command halt., or simply type CTRL-d at the SWI-Prolog prompt.

How do I stop backtracking in Prolog?

Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop.

What does the exclamation point mean in prolog?

Prolog provides a predicate that performs this function. It is called the cut, represented by an exclamation point (!). The cut effectively tells Prolog to freeze all the decisions made so far in this predicate. That is, if required to backtrack, it will automatically fail without trying other alternatives.

How does prolog solve a query?

The unique feature of Prolog is that it automatically chooses the facts and rules needed to solve a query. But how does it make its choice? It starts by trying to solve each goal in a query, left to right (recall goals are connected using “,” which is the and operator).


1 Answers

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), !.
like image 65
Yasel Avatar answered Sep 26 '22 18:09

Yasel