Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you append an element to a list in place in Prolog?

Tags:

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.

like image 791
No One in Particular Avatar asked Feb 22 '13 16:02

No One in Particular


People also ask

How do I add elements in front of a list in 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 '.

How do you select an element in a list in Prolog?

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).


2 Answers

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.

like image 189
S.L. Barth Avatar answered Sep 22 '22 11:09

S.L. Barth


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.

like image 40
mndrix Avatar answered Sep 22 '22 11:09

mndrix