Search code examples
listvariablesprolog

Compare list in prolog


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].

Solution

  • 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.