简体   繁体   中英

Defining membership rule in prolog

Currently I am studying prolog programming. While I am studying member list (if element is there on list)it show an error when I am consulting.

?- 
Warning: c:/users/h.m.thaheed/pictures/snippingtool++/uploads/exx.pl:1:
Singleton variables: [R]
Warning: c:/users/h.m.thaheed/pictures/snippingtool++/uploads/exx.pl:2:
Singleton variables: [Y]

Rule has follows:

member(X,[X|R]).
member(X,[Y|R]) :- member(X,R).

Please help me to solve this.

Those are not errors, but warnings. The Prolog interpreter warns that it can only find one occurrance of one or more variables, which is strange, since typically variables are used to perform unification, pass values from one predicate to another, etc.

Defining a variable a single time makes only sense as a placeholder : when you need to specify a variable to perform correct unification. But Prolog has a standardized way to do that: with an underscore _ . You can see an underscore as a "throw away variable". If a predicate contains two (or more) underscores, then those are two (different) variables. The purpose of the underscores is to make it clear that this is a placeholder, and it will thus suppress the warning.

You can thus rewrite the predicate to:

member(X,[X|_]).
member(X,[_|R]) :- member(X,R).

Note that many implementations of member/2 use a member/3 helper predicate to avoid unpacking each "cons" (list element) twice, for example in SWI-Prolog we see:

 member(El, [H|T]) :- member_(T, El, H). member_(_, El, El). member_([H|T], El, _) :- member_(T, El, H).

So here we unpack the list in parameters of the predicate call. This means that the first clause and the second clause of member_ do not need to perform unpacking in the head (we here make some assumptions as to how the interpreter exactly works of course), and in the last clause of member_ , we only unpack the next cons once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM