append/3
append(
?List1,
?List2,
?List3)
A list consisting of List1 followed by List2.
Appends lists List1 and List2 to form List3:
| ?- append([a,b], [a,d], X). X = [a,b,a,d] | ?- append([a], [a], [a]). no | ?- append(2, [a], X). no
Takes List3 apart:
| ?- append(X, [e], [b,e,e]). X = [b,e] | ?- append([b|X], [e,r], [b,o,r,e,r]). X = [o,r] | ?- append(X, Y, [h,i]). X = [], Y = [h,i] ; X = [h], Y = [i] ; X = [h,i], Y = [] ; no
Suppose L is bound to a proper list. That is, it has the form [T1,...,Tn] for some n. In that instance, the following things apply:
append(
L,
X,
Y)
has at most one solution, whatever X and Y are, and
cannot backtrack at all.
append(
X,
Y,
L)
has at most n+1 solutions, whatever X and Y are, and
though it can backtrack over these it cannot run away without finding
a solution.
append(
X,
L,
Y)
, however, can backtrack indefinitely if X and Y are
variables.
The following examples are
perfectly ordinary uses of append/3
:
To enumerate adjacent pairs of elements from a list:
next_to(X, Y, (*in*) List3) :- append(_, [X,Y|_], List3).
To check whether Word1 and Word2 are the same except for
a single transposition. (append/5
in library(lists)
would be
better for this task.)
one_transposition(Word1, Word2) :- append(Prefix, [X,Y|Suffix], Word1), append(Prefix, [Y,X|Suffix], Word2). | ?- one_transposition("fred", X). X = "rfed" ; X = "ferd" ; X = "frde" ; no
Given a list of words and commas, to backtrack through the phrases delimited by commas:
comma_phrase(List3, Phrase) :- append(F, [','|Rest], List3), !, ( Phrase = F ; comma_phrase(Rest, Phrase) ). comma_phrase(List3, List3). | ?- comma_phrase([this,is,',',um,',',an, example], X). X = [this,is] ; X = [um] ; X = [an,example] ; no
ref-lte-acl,
library(lists)
.