Friday 15 February 2019

Prolog: Check for existence of an element in the list


Implement a ‘contains’ rule, that takes two arguments, first argument is the element to search for and second argument is the list of elements. ‘contains’ rule should return true, if the element exists in the list, else false.

We can solve this problem using list pattern matching.

contains(X, [X|_]).
contains(X, [Y|Z]) :- contains(X, Z).

Above snippet is used to find the existence of an element in the list. First statement, checks the element X with head of the list, if it matches, it return true. If the head element is not matched with the element X, then we fall back to second rule, it repeats the same using tail of the list.

listDemo.pl
contains(X, [X|_]).
contains(X, [Y|Z]) :- contains(X, Z).

1 ?- consult(listDemo).
Warning: c:/users/public/prologexamples/listdemo.pl:2:
        Singleton variables: [Y]
true.

2 ?- contains(2, []).
false.

3 ?- contains(2, [2]).
true .

4 ?- contains(2, [0, 2]).
true .

5 ?- contains(2, [0, 2, 4]).
true .


You can use ;, to check all the occurrences of the element in the list.

6 ?- contains(2, [0, 2, 4, 2, 3]).
true ;
true ;
false.



Previous                                                 Next                                                 Home

No comments:

Post a Comment