The Many Uses Of Append/3

One of the great things about prolog is the ability to reverse predicates and call them in many different ways. This leads to quite flexible programs if done write and is pretty fun as well sometimes. append/3 is a staple for prolog and an exploration of some of its uses is required.

  1. Append one list to another

    ? append([a,b,c],[d,e,f],L).
    L = [a,b,c,d,e,f]
  2. Verify that a list is one list appended to another

    ? append([a,b,c],[d,e,f],[a,b,c,d,e,f]).
  3. Remove a prefix from a list.

    ? append([a,b,c],X,[a,b,c,d,e,f]).
    X = [d,e,f]
  4. Remove a suffix from a list.

    ? append(X,[d,e,f],[a,b,c,d,e,f]).
    X = [a,b,c]
  5. Determine if a pattern exists.

    ? append(_,[c,d|_],[a,b,c,d,e,f]).
  6. Get all characters between a prefix and suffix

    ? append([a,b|X],[e,f],[a,b,c,d,e,f]).
    X = [c, d]
  7. Get the first X characters.

    ? length(X, 3), append(X,_,[a,b,c,d,e,f]).
    X = [a,b,c]
  8. Get the last X characters.

    ? length(X, 3), append(_,X,[a,b,c,d,e,f]).
    X = [d,e,f]
  9. Remove the first X characters from a list

    ? length(X, 2), append(X,Y,[a,b,c,d,e,f]).
    X = [a,b]
    Y = [c,d,e,f]
  10. Remove the last X characters from a list

    ? length(X, 2), append(Y,X,[a,b,c,d,e,f]).
    X = [e, f],
    Y = [a, b, c, d]
  11. Find the last element of a list

    ?- append(_, [X], [a,b,c,d,e,f]).
    X = f