简体   繁体   中英

Implementing a stack in Prolog

I need a way of doing the following in Prolog.

I want to have a list of variables defined. For example [x,z,k,s,r,v,w]

And then I want one of my functions to be able to pop the first element from the list, use it in some way, then when It needs another element I want it to pop the next element from that list. And perhaps when the function is finished I want it to reset the list to it's original state.

I can't think of a way of doing this by simple passing the list as an argument. This would be really simple with OO programming. As I could just have a global variable.

I'm not sure I fully understand your question, but I think a stack is pretty simple to implement.

pop([X|List],X,List). will unify the head of the list with X, so you can you can use it as you wish. And push(X,List,[X|List]) will unify the third argument a new List with X pushed at its head.

Or maybe I totally did't get you question...

Please note that the stack is implemented in a pure side effect free manner. Since no implicit state is used, everything has to be explicit. Usually, Prolog programmers use lists directly, or they use grammars (DCGs) for that purpose.

empty([]).

pop(E, [E|Es],Es).

push(E, Es, [E|Es]).


| ?- empty(S0), push(1,S0,S1),push(2,S1,S2),pop(T,S2,S3).
S0 = []
S1 = [1]
S2 = [2,1]
T = 2
S3 = [1]

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