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, ie append(A,B,C) to get A and B concatenated to the list C.
I can do this with a temporary list Y = [1, 2, 3, 4] and Z = [5], to then do an append(Y, Z, X), but I don't like having a temporary list.
The usual disclaimers apply here - this is not homework and I am just learning Prolog.
To add an element at the beginning of a list, just use list notation: pushFront(Item, List, [Item|List]). The list representation uses internally the cons functor ( . ), so a list [b,c,d] is just syntactic sugar for '.
This predicate can be used to select an element from a list, delete an element or insert it. The definition of this Prolog library predicate is: select(A, [A|B], B). select(A, [B, C|D], [B|E]) :- select(A, [C|D], E).
As the others have pointed out, you're going to be stuck with the performance issue.
But just as an exercise I decided to try and create a predicate that could append an element to the end of a list, without using append
.
% add_tail(+List,+Element,-List) % Add the given element to the end of the list, without using the "append" predicate. add_tail([],X,[X]). add_tail([H|T],X,[H|L]):-add_tail(T,X,L).
I would advice that you'd simply use the append
function, as a built-in function it is likely to be faster than anything manually crafted.
Variables in Prolog can only be assigned once. As soon as X has the value [1,2,3,4] it can never have another value. A temporary variable and append/3, like you mentioned, is the way to do it.
Having said that, you can do one trick which probably isn't recommended. If X = [1,2,3,4,Y] then you can do Y=5 and X now has the value you want. I believe this technique is called a difference list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With