Reputation: 323
In the code below, I am trying to search through a list and print "match" if there's a match in the list and print "no match" if there's no match. My code prints "match" if there's a match but, doesn't print "no match" instead returns false if there's no match. How can I change my code to print "no match" if there's no match in the list? thanks
on(Item,[Item|_], X) :- X is 1.
on(Item,[_|Tail],X):- on(Item,Tail,X).
check(X,Y) :- on(X,Y,Z), (Z == 1, write('match');write('no match')).
Upvotes: 2
Views: 3380
Reputation: 9850
You need to add a clause that catches the case when on
reaches the end of the list:
on(_, [], X) :- X is 0.
However, in order to make that work, you need to put a cut operator, !
, into the matching on
clause, so that it doesn't continue and find the empty list matching clause also:
on(Item,[Item|_], X) :- X is 1, !.
Also, it looks like your printing code isn't doing what you want it to do, I think it should look something like:
(Z == 1 -> write('match'); write('no match')).
(note the ->
in there). I'm not positive that's correct, but I had to change it to make it work correctly on mine.
Finally, to make your code look a little bit prettier, you can put the X is 0
and X is 1
stuff into the predicate itself, so it becomes:
on(_, [], 0).
on(Item, [Item|_], 1) :- !.
Upvotes: 3