Search code examples
prologappend

Prolog, understanding append/3


?- append([], [X1], [a,b]).

Why does this return no and not

X1 = a,b

Since

? - append([], [a,b], [a,b])

returns yes?


Solution

  • See: append/3

    append(?List1, ?List2, ?List1AndList2)
    

    List1AndList2 is the concatenation of List1 and List2


    So for

    ?- append([], [X1], [a,b]).
    

    [] is the empty list and [X1] is a list with a variable X1

    If you run the query like this

    ?- append([],[X1],A).
    

    you get

    A = [X1].
    

    which means that A is the concatenation of [] and [X1].

    In your query it is asking if the concatenation of [] and [X1] is [a,b] which is false, or no.


    For your second query

     ? - append([], [a,b], [a,b])
    

    it is asking if the concatenation of [] and [a,b] is [a,b] which is true, or yes.