Make Prolog return one solution and stop showing the query option

user3026297 picture user3026297 · Nov 24, 2013 · Viewed 10.5k times · Source

I'm new to prolog, and am experimenting with how to get it to stop querying after it finds one answer. I'm using this code:

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

The result is:

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

true ? a

yes

I'm lost as to how I could get Prolog to stop printing "true ?" and just print "yes" instead. I've tried using if/else construct and the format function but it still prints "true ?". Any ideas?

Answer

Shon picture Shon · Nov 24, 2013

You're cutting the wrong place. Cut after the base condition, which says, "once the base is met, don't backtrack any more":

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

If-then does work for me, perhaps you implemented it different? (on 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 the error pointed out by false.