Prolog Language Getting started with Prolog Language append/3


Example

append([], Bs, Bs).
append([A|As], Bs, [A|Cs]) :-
    append(As, Bs, Cs).

append/3 is one of the most well-known Prolog relations. It defines a relation between three arguments and is true if the third argument is a list that denotes the concatenation of the lists that are specified in the first and second arguments.

Notably, and as is typical for good Prolog code, append/3 can be used in several directions: It can be used to:

  • append two fully or partially instantiated lists:

      ?- A = [1, 2, 3], B=[4, 5, 6], append(A, B, Y)
      Output:
      A = [1, 2, 3],
      B = [4, 5, 6],
      Y = [1, 2, 3, 4, 5, 6].
    
  • check whether the relation is true for three fully instantiated lists:

      ?- A = [1, 2, 3], B = [4, 5], C = [1, 2, 3, 4, 5, 6], append(A, B, C)
      Output:
      false
    
  • generate all possible ways to append two lists to a given list:

      ?- append(A, B, [1, 2, 3, 4]).
      Output:
      A = [],
      B = [1, 2, 3, 4] ;
      A = [1],
      B = [2, 3, 4] ;
      A = [1, 2],
      B = [3, 4] ;
      A = [1, 2, 3],
      B = [4] ;
      A = [1, 2, 3, 4],
      B = [] ;
      false.