How to return to Prolog both a variable result and true / false?

It sounds silly, but lets say that my most / 2 predicate returns the largest element in the list ... the output should look like this:

?- largest([1,2,3,4,5], X). X = 5. false. 

I have implemented the largest one and it works as above, except that it does not display "false". How to do this so that it also displays this "false". cost? This is for the annoying job I have to finish. :(

+4
source share
4 answers

This extra false. or No means that the person running the program asked for all possible solutions for X , and not just the first possible solution.

In most Prolog interactive interpreters, you check if there is another solution by pressing the semicolon key ( ; ).

+8
source

sounds impossible, as if the predicate fails, there is no binding of free variables, see

  ?- A=5. A = 5. ?- A=5,false. false. 

but

  ?- A=5;false. A = 5 ; false. 

To achieve this, you must make your predicate "largest" non-deterministic. But to me it seems pretty dumb.

+1
source

If this was part of the assignment, this probably means that your predicate should not give a second (possibly different) result after backtracking. Rollback occurs if the user wants the next solution, often by clicking ; . The interpreter often indicates that another solution is possible when he knows that paths that have not been fully appreciated have yet to be completed.

Suppose you had the predicate foo/1 as follows:

 foo(1). foo(Bar) :- foo(Baz), Bar is Baz + 1. 

If you ask foo(Bar) , the interpreter will respond with Bar = 1 . After repeated pressing ; the interpreter will return with Bar = 2 , Bar = 3 , etc.

In your example, finding the largest list should be deterministic. Rollback should not give another answer.

You need to interpret the assignment as meaning that you must allow backtracking but fail, or it would be nice to not even have it back.

+1
source

Previous answers have @aschepler , @Xonix, and @SQB .

In this answer, we use to express declarative integer arithmetic.

 :- use_module(library(clpfd)). 

We define largest/2 using the built-in member/2 predicate, the maplist/2 library, and the end-region constraint (#>=)/2 :

 largest(Zs, X) :- member(X, Zs), % X is a member of the list Zs maplist(#>=(X), Zs). % all Z in Zs fulfill X #>= Z 

Request examples:

 ?- largest([1,2,3,4,5], X). X = 5. ?- largest([1,2,3,4,5,4], X). X = 5 ; false. ?- largest([1,2,3,4,5,5], X). X = 5 ; X = 5. ?- largest([1,2,3,4,5,5,4], X). X = 5 ; X = 5 ; false. ?- largest([A,B,C,D], X). A = X, X#>=D, X#>=C, X#>=B ; B = X, X#>=A, X#>=D, X#>=C ; C = X, X#>=A, X#>=D, X#>=B ; D = X, X#>=A, X#>=C, X#>=B. 
0
source

All Articles