Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Checking Member of A List



Prolog provides an inbuilt method member to check if an element is part of a List or not.

Syntax

member(E, List)

Where

  • E − element to be searched in the List.

  • X − List to be serached.

It returns true if element found in the list else returns false.

GNU Prolog 1.5.0 (64 bits)
Compiled Jul  8 2021, 12:33:56 with cl
Copyright (C) 1999-2021 Daniel Diaz

| ?- member(b,[a,b,c]).

true ? ;

no
| ?- member(d,[a, b, c]).

no
| ?- 

Here we receives true when member(b,[a,b,c]) is called and no when member(d,[a,b,c]) is called as d is not a member of the list.

Custom Membership Operation

We can define our own custom implementation of membership operation as shown below −

During this operation, we can check whether a member X is present in list L or not? So how to check this? Well, we have to define one predicate to do so. Suppose the predicate name is list_member(X,L). The goal of this predicate is to check whether X is present in L or not.

To design this predicate, we can follow these observations. X is a member of L if either −

  • X is head of L, or

  • X is a member of the tail of L

Program (list_basics.pl)

list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).

Output

| ?- consult('D:/TP Prolog/Sample Codes/list_basics.pl').
compiling D:/TP Prolog/Sample Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample Codes/list_basics.pl compiled, 3 lines read - 780 bytes written, 3 ms

yes
| ?- list_member(b,[a,b,c]).

true ? ;

no
| ?- 
Advertisements