Compare list in prolog

Viewed 62

I just started learning prolog and i don't understand why this returning false. I tried find solutions, but i not found. Can someone tell me why this return false?

[[A],B,C]=[[a,b,c],[d,e,f],1].
2 Answers

Short answer: [A] is a singleton list, but the corresponding element [a,b,c] has three elements.

You aim to match [[A], B, C] with [[a,b,c], [d,e,f], 1]. This thus means that you want to match a list with three elements with [[a,b,c], [d,e,f], 1]. Furthermore it means that you want to match [A] = [a,b,c], B = [d,e,f] and C = 1. The [A] can however not match with [a,b,c], since [A] means a singleton list.

You probably want to match this with [A,B,C] instead:

?- [[A],B,C]=[[a,b,c],[d,e,f],1].
false.

?- [A,B,C]=[[a,b,c],[d,e,f],1].
A = [a, b, c],
B = [d, e, f],
C = 1.

If you want to match with a non-empty list, with A the first element, you can match this with [A|_] instead:

?- [[A|_],B,C]=[[a,b,c],[d,e,f],1].
A = a,
B = [d, e, f],
C = 1.

Here is another way to answer why your query fails using library(diadem):

?- [[A],B,C]=[[a,b,c],[d,e,f],1].
   false.
?- [[A],B,C]=[[a,b,c],[d,e,f],1].?X.
   X = ([[A]|_]=[[_,_|_]|_])                        /* 1 */
;  X = (dif(A100,B100),[[A|A100]|_]=[[_|B100]|_])   /* 2 */
;  X = (dif(A100,B100),[A100|_]=[B100|_])           /* 3 */
;  X = (dif(A100,B100),A100=B100)                   /* 4 */
;  ... .

Here the system generates most general generalizations that still fail.

The first generalization removes all irrelevant parts, what remains is this [A] and [_,_|_].

The second generalization insists that the tail of both lists is just different (instead of insisting that they are [] and [_|_] as stated in the first generalization).

The third and fourth are just more general views of it.

Related