I have defined a code in PROLOG :
is_member(X, [X|_]).
is_member(X, [_|T]) :-
is_member(X, T).
I am confused by these two outputs :
out1:
is_member('a', ['b', 'c', 'd', 'a']).
>> True.
out2:
Chars = ['b', 'c', 'd', 'a'].
is_member('a', Chars).
>> Chars = [a|_2356]
Can someone help me out here? I though that output should be True.
. I am trying to understand the logic here, but obviously I am lost.
Thank you for any help or advice in advance.
Here's how Prolog queries basically work.
First of all, a complete query ends with a period (.
). When you execute:
Chars = [a, b, c, d].
This is a complete query since it ends in a period. When you execute a query, Prolog attempts to make it succeed via some binding of the given variables. If it is able to do so, it will simply display the variable bindings that result in success. In this particular case, the solution is trivial: Chars
is bound to [a, b, c, d]
.
Suppose you enter the above and then you follow this with:
is_member(a, Chars).
Since the previous query completed (it ended in a period), Prolog sees this Chars
as a new variable. It is no longer bound to [a, b, c, d]
because the previous query ended. Prolog looks at this query and determines what binding(s) for Chars
will cause it to succeed. The result is:
Chars = [a|_2356]
Prolog is telling you that a valid solution is obtained by binding Chars
to the list [a|_2356]
which is any list that has a
as its first element. What you didn't show is that Prolog prompts for additional solutions. If you press ;
, it shows you more solutions to the is_member(a, Chars).
query:
3 ?- is_member(a, Chars).
Chars = [a|_5034] ;
Chars = [_5032, a|_5040] ;
Chars = [_5032, _5038, a|_5046] ;
...
In other words, is_member(a, Chars)
has an infinite number of solutions. They are lists that have a
as the first element, a
as the second, etc.
In Prolog, if you want to establish a series of conditions that must all be true in sequence, you use a comma, not a period, to separate each condition, then end the whole thing in a period:
4 ?- Chars = [a,b,c,d], is_member(a, Chars).
Chars = [a, b, c, d] ;
false.
This query says you want to bind Chars
to [a, b, c, d]
and determine if a
is a member of Chars
. Prolog is then saying that it succeeded with one solution, Chars = [a,b,c,d]
. Entering ;
seeks more solutions, which comes back false since there are no additional solutions.
Let's try Isabella's other example with x
:
5 ?- Chars = [a,b,c,d], is_member(x, Chars).
false.
In this case, Prolog could not find a solution, so it simply fails (showing false).