0
votes

I have a question about append elements to a given list, I know this could be done by 3 variable predicate: append([Item], List, [Item | List]). How about using only two variables, can it also be achieved, like append([Item], List), where List is the existing list?

2

2 Answers

1
votes

CapelliC's answer is perfectly correct. I just want to add, for clarity, that Prolog predicates do not have return values in the way that functions or procedures in other languages do. There are multiple reasons behind this (and much written about logical programming). For now, keep in mind that the strength of a predicate like append/3 is that it can not only append two lists to form a new list, but also split a list in two:

?- append(Start, [c,d,e], [a,b,c,d,e]).

Or even enumerate all possible splits of a list (non-deterministic):

?- append(X,Y,[a,b,c]).

A fully instantiated list, like [a,b,c] (without variables in it) cannot be changed within the context of a Prolog predicate. You can only instantiate a new list which, in the case of append, has additional elements.

0
votes

You need 3 elements: the element to be added, the list without element, the concatenation of these. Then you can't do with 2 elements only.

Note that append([Item], List, Result) can be more conveniently written [Item|List] = Result, and Item will be the first element of Result. Then you're not appending. You can do with append(List, [Item], Result)