Sedg
Sedg

Reputation: 1

Prolog recursively checking if an item is in a list

So I am trying to write a piece of code that checks to see if an item is in a list or not.

is_member(_,[]).
is_member(X,[X|_]).
is_member(X,[_|tail]):- is_member(X,tail).

this is currently what I have for the code. It works if the item is in the first position but doesn't check the rest of the list. Can anyone help me figure out what i'm doing wrong? Thanks.

Upvotes: 0

Views: 589

Answers (1)

Sam Segers
Sam Segers

Reputation: 1951

Your predicates faces the following two problems:

  • The base case is_member(_,[]). will always return true for an empty list, which is not correct; and

  • Your variable should start with an Uppercase character: Tail.

An example how to implement a predicate that solves these two issues:

is_member(X,[X|_]).
is_member(X,[_|Tail]):- is_member(X,Tail).

Upvotes: 2

Related Questions