Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append element to beginning of list in Prolog

Tags:

list

prolog

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?

like image 250
MathuSum Mut Avatar asked Feb 08 '23 03:02

MathuSum Mut


1 Answers

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

like image 127
gusbro Avatar answered Feb 16 '23 03:02

gusbro