/* File: stack0.pl System: SWI-Prolog 5.2.8 Author: Mihaela Malita Date: 10/23/2003 Title: A STACK in Prolog ?- push(a). Yes ?- push(b). Yes ?- push(c). Yes ?- print_stack. Stack is: [c, b, a] ?- pop(I). I = c ?- look(X). X = b ?- pop(I). I = b ?- pop(I). I = a ?- empty_stack. Yes ?- print_stack. Stack is: [] *************************************************/ % declare stack as "dynamic" so you can change it :-dynamic(stack/1). % intially the stack is empty. stack([]). % push something H in your stack. Remove old stack and put new stack instead push(H):- stack(L),New=[H|L],retract(stack(_)),assert(stack(New)). % pop something out of the stack pop(H):- stack([H|L]),retract(stack(_)),assert(stack(L)). % check if stack is empty empty_stack:- stack([]). % look at the top of the stack. Do not do anything. look(Top):- stack([Top|_]). % print the stack print_stack:- stack(L),write('Stack is: '),write(L).