How do I append an element to the beginning of a list in Prolog? I need the end result to be called like so:
pushFront(8, [3, 1], NewList). % NewList is now [8, 3, 1].
I have tried to implement it as follows:
pushFront(Item, [], [Item|_]). %Problematic
pushFront(Item, [OldDequeH|OldDequeT], NewDeque) :-
leftPush(OldDequeH, OldDequeT, [Item|NewDeque]).
But it does not work, and I'm out of ideas tbh. Can anyone describe what is wrong with my implementation and what changes it needs to work properly?
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 '.'(b,'.'(c, '.'(d, [])))
.
This representation allows you to add an item at the front just by wrapping another cons functor, i.e. if you want to a add an item a at the front of a list L
you would wrap a '.'(a, L)
, which we usually write simply as [a|L]
.
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