简体   繁体   中英

Append element to beginning of list in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM