:-consult(grammar-2). % grammar rules have the format LHS ---> [RHS] parse(X,[s(X)], []). % Success state. parse(X,Stack, L):- % If TOS corresponds to a RHS, reduce(Stack, [], NewStack), % reduce the stack parse(X,NewStack, L). % parse the new stack parse(X,Stack, [Word|L]):- % If TOS is word, parse(X,[Word|Stack], L). % read it, push it and recurse. reduce(Stack, RHS, [LHS|Stack]):- % The accumulator matches RHS (LHS ---> RHS). % so LHS is pushed reduce([NT|Stack],Acc,NewStack):- % If it does not, pop NT to Acc reduce(Stack,[NT|Acc],NewStack). % and recurse.