user1913592
user1913592

Reputation: 165

append two incomplete lists in prolog

L = [a, b, c|_]. - an example of an incomplete list. how do I append two of these? How do I reverse an incomplete list? Can someone give me tips how to deal with these in general?

append([x|t],y,[x|r]):-append(t,y,r). This is how two lists are appended.

Upvotes: 2

Views: 1055

Answers (1)

CapelliC
CapelliC

Reputation: 60034

for instance

?- A=[1,2,3|X], B=[a,b,c|Y], X=B.
A = [1, 2, 3, a, b, c|Y],
X = B, B = [a, b, c|Y].

These patterns are of little utility.

As @Daniel Lyons suggests, you can as well use append/3

?- A=[1,2,3|X], B=[a,b,c|Y], append(A,B,C).
A = [1, 2, 3],
X = [],
B = [a, b, c|Y],
C = [1, 2, 3, a, b, c|Y] 

You can see the difference between those patterns: first directly binds X to B (1 inference), while append requires a number of inferences equal to first list length, to reach the tail before binding.

You can read more about incomplete data structures here. The most useful pattern is difference lists, the base for .

Upvotes: 2

Related Questions