Search code examples
prolog

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.


Solution

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