William McCarty
William McCarty

Reputation: 839

confused about Prolog Response

Consider:

bar([], Ws, Ws).
bar([X|Xs], Ys, [X|Zs]) :- bar(Xs, Ys, Zs).

1) How does this have no Solutions

bar([1,2], [], [X,X]).

2) How does this have only One Solution when Z=5?

bar([5,Y], [Y,5], [Z,Z|_]).

3)How does this have only One Solution when Z=5 and Y = 5?

bar([_,Y], [5,5], [Z,Z,Z|_]).

Upvotes: 1

Views: 35

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

First, consider the meaning of bar/3: the rule has three arguments representing lists. bar/3 returns a solution when the last list is a concatenation of the first two:

bar([1,2,3], [4,5], X)       // X=[1,2,3,4,5]
bar([1,2,3], X, [1,2,3,4,5]) // X=[4,5]
bar(X, [4,5], [1,2,3,4,5])   // X=[1,2,3]

Knowing this, you can figure the answers to all your questions:

  • bar([1,2], [], [X,X]). needs X to unify with 1 and 2 at the same time, which is impossible
  • bar([5,Y], [Y,5], [Z,Z|_]). unifies 5 with the first Z, and the second Z with Y, for a single solution
  • bar([_,Y], [5,5], [Z,Z,Z|_]). unifies Y with the second Z, and the third Z with 5, for a single solution.

Upvotes: 1

Related Questions