[ACCEPTED]-Implement the member predicate as a one-liner-dcg
Solution:
member(X, [Y|T]) :- X = Y; member(X, T).
Demonstration:
?- member(a, []). fail. ?- member(a, [a]). true ; fail. ?- member(a, [b]). fail. ?- member(a, [1, 2, 3, a, 5, 6, a]). true ; true ; fail.
How it works:
- We are looking for an occurrence of the first argument,
X
, in the the second argument,[Y|T]
. - The second argument is assumed to be a list.
Y
matches its head,T
matches the tail. - As a result the predicate fails for the empty list (as it should).
- If
X = Y
(i.e.X
can be unified withY
) then we foundX
in the list. Otherwise (;
) we test whetherX
is in the tail.
- We are looking for an occurrence of the first argument,
Remarks:
- Thanks to humble coffee for pointing out that using
=
(unification) yields more flexible code than using==
(testing for equality). This 7 code can also be used to enumerate the elements 6 of a given list:
?- member(X, [a, b]). X = a ; X = b ; fail.
And it can be used to "enumerate" all 5 lists which contain a given element:
?- member(a, X). X = [a|_G246] ; X = [_G245, a|_G249] ; X = [_G245, _G248, a|_G252] ; ...
Replacing 4
=
by==
in the above code makes it a lot less 3 flexible: it would immediately fail onmember(X, [a])
and 2 cause a stack overflow onmember(a, X)
(tested with 1 SWI-Prolog version 5.6.57).
- Thanks to humble coffee for pointing out that using
Since you didn't specify what other predicates 2 we're allowed to use, I'm going to try and 1 cheat a bit. :P
member(X, L) :- append(_, [X|_], L).
newmember(X, Xs) :-
phrase(( ..., [X] ),Xs, _).
With
... --> [] | [_], ... .
Actually, the following definition also 5 ensures that Xs
is a list:
member_oflist(X, Xs) :-
phrase(( ..., [X], ... ), Xs).
Acknowledgements
The first appearance 4 of above definition of ...
is on p. 205, Note 3 1 of
David B. Searls, Investigating the Linguistics 2 of DNA with Definite Clause Grammars. NACLP 1 1989, Volume 1.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.