Make Prolog return one solution and stop showing request parameter

I'm new to the prologue, and I'm experimenting with getting him to terminate the request after he finds one answer. I am using this code:

member1(L,[L|_]). member1(L,[_|RS]) :- member1(L,RS),!. 

Result:

 | ?- member1(3,[3,2,3]). true ? a yes 

I got lost on how to get Prolog to stop printing "true?". and just type yes. I tried using the if / else construct and the format function, but it still prints "true?". Any ideas?

+6
source share
2 answers

You are carrying the wrong place. Cut after the base condition, which says: "as soon as the base is completed, do not back down anymore":

 member1(L,[L|_]) :- !. member1(L,[_|RS]) :- member1(L,RS). 

If-then really works for me, maybe you implemented it in different directions? (by swi-prolog)

 member1(X,[Y|RS]) :- ( X = Y -> true ; member1(X,RS) -> true ; false ) . 

Swi also has the predicate once/1 .

edited to account for errors indicated by false.

+3
source

From the output you are showing, I assume you are using GNU Prolog. But first, just an important point:

The cutout you cut is not cut off as you intend it! In fact, this does not even prevent the fact that there is one answer. Here is the evidence for this:

 | ?- member1(X,[1,2,3]). X = 1 ? ; X = 2 yes 

So you still have two answers. Typically: shortening after a recursive target often does some unexpected things.

If you insist on getting the first answer, just say once(member(X,[1,2,3])) . once/1 is also a cut, but it is pretty hidden. This is tamed to do exactly one thing. Yes, you can also cut recursive rules, but for beginners it is better to leave this in a later lesson.

Behind all this, there is another point that is less visible: the toplevel GNU Prolog shell will offer you further solutions if you see an open alternative (jargon: point of choice). Therefore, when GNU asks you to find out more, it knows that some part has yet to be explored, but there is no guarantee that there is actually another answer:

 ?- member(1-X,[1-a,2-b,3-c]). X = a ? ; no 

Here, the top layer sees an open selection and, therefore, asks if you want to continue studying the query. Alas, this search in Vienna ...

+2
source

Source: https://habr.com/ru/post/958737/


All Articles