1
votes

I just started learning Prolog and my task is to write a predicate poklapanje(M,V) which returns yes if all the elements of list M are the first elements of list V, for example poklapanje([1,2],[1,2,3]) should return yes. The first question I have is what is the difference between true and yes, because I am getting true in my solution? Second, when I type poklapanje(X,[1,2,3]) I should get:

X = [];
X = [1];
X = [1,2];
X = [1,2,3];
no

and I get:

X = [];
false

Why? I guess it has something to do with my implementation and printing true/false instead of yes/no.

Here is my code:

poklapanje([],[_|_]).
poklapanje([A|B],[C|D]):- A == C, poklapanje(B,D).
2

2 Answers

5
votes

There is no difference between yes and true. It's just difference between Prolog implementations. For example, we get true in SWI-Prolog, and yes in GNU Prolog.

I'm not sure how you posed your query. Here's the output from running your code:

?- poklapanje(X,[1,2,3]).
X = [] ;
X = [1] ;
X = [1, 2] ;
false.

It's missing [1, 2, 3] because poklapanje([],[_|_]). fails for poklapanje([],[]).

I would implement it like this:

poklapanje([], _).
poklapanje([A|B],[A|D]) :- poklapanje(B,D).
2
votes

Since I cannot add a comment (not enough reputation), i'm putting this here. I'll try to explain why your code doesn't work and why Fabricator's code works.

First problem you have, is

A == C

which is not doing what you wanted to achieve. Instead, you want to unify variables, so use

A = C

or even better, as suggested in the correct answer

poklapanje([A|B],[A|D])

If you do it with A == C, in the second step you would have 1 == C, and this will fail as C is not equal to 1.

Second issue, which is already explained, is

poklapanje([],[_|_]).

which will fail in the last step, where D is an empty list. Empty list doesn't have any members, so it will not unify with [ _ | _ ]. You might be tempted to use [ _ ] to fix this problem, but that would unify only with the list which has one member. That's why you have to use _, which will unify with any list:

poklapanje([], _).

Hope it clears it up for you a bit. :-)