0
votes

I am just learning Prolog and stumbled across following question: Prolog - Seeing if the same element occurs in two lists.

This question includes following line: =(member(X,[H|T]), member[Z|Q])).

I know about member(?Elem, ?List), but I do not understand the member[Z|Q] part. What does this mean? And isn't there a closing paranthesis too much?

1

1 Answers

2
votes

Summary:

Do not worry about this at all.

Here are several reasons:

Syntax error

First of all, this is invalid syntax. When you consult the program you link to, you get:

ERROR: file.pl:5:28: Syntax error: Operator expected

indicating exactly the line containing:

    =(member(X,[H|T]), member[Z|Q])),

Dubious meaning

Second, even if we somehow fix the problematic syntax, and write this line for example as:

    =(member(X,[H|T]), member_whatever),

Then it would still be highly dubious that this is what the author meant to express.

The predicate that is used in this case is (=)/2, and you can write this equivalently using infix notation as:

    member(X,[H|T]) = member_whatever,

And from this, it is already clear that this cannot succeed because (=)/2 does not even hold for the much more general case

    member(_,_) = member_whatever,

So, it definitely fails of course also in the more specific case above!

Fundamental issues

When programming in Prolog, focus on a clear description of what holds.

For example, to state that "the same elements occurs in two lists" is straight-forward:

element_in_both(E, As, Bs) :-
     member(E, As),
     member(E, Bs).

That's it! You can read it as follows: If E is a member of As and E is a member of Bs then E is a member of both As and Bs.

It works quite generally, for example:

?- length(Cs, _),
   append(As, Bs, Cs),
   element_in_both(E, As, Bs).
Cs = [E, E],
As = Bs, Bs = [E] ;
Cs = [E, E, _2946],
As = [E],
Bs = [E, _2946] ;
Cs = [E, _2940, E],
As = [E],
Bs = [_2940, E] .

You can use this predicate to generate lists where this relation holds, to test whether it holds for a specific instance, to complete partial lists such that they satisfy this predicate etc.

All of this follows from a clear declarative description of the conditions that make this relation hold.

In Prolog courses, there is a tendency to needlessly complicate this rather simple fundamental principle of declarative programming. Do not fall into this trap. If your predicate becomes convoluted, your are often overlooking something simpler.