If I have a list in Prolog such as X = [1, 2, 3, 4], how do I add the element 5 to the end of the list to have X = [1, 2, 3, 4, 5]?
The append function needs two lists
One declarative solution is to use a difference list (as Daniel suggested in its answer). A difference list gets its name from being usually represented as a difference between two lists: a list and its tail. For example, an empty list can be represented as T-T
. A list with the elements 1, 2, and 3 can be represented as [1,2,3| T]-T
(note that (-)/2
is standard built-in infix operator). The advantage of this representation is that you can append an element to a list in constant time by using a single fact definition of the append/3
predicate:
append(L1-T1, T1-T2, L1-T2).
An usage example:
?- append([1,2,3,4| T1]-T1, [5| T2]-T2, Result).
T1 = [5|T2],
Result = [1, 2, 3, 4, 5|T2]-T2.
If necessary, is not difficult to convert between a "normal" list and a difference list. I leave that as an exercise to you.