在http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/contents.html上有一个prolog的DFA parser,于是通读理解以后,模仿着写了一个PDA parser。
PDA(pushdown automata)是接受上下文无关语言的装置,这里我使用了一个例子,其生成的语言为{a,b}上的回文。
%2013-01-27
%% PDA Parser
%% Author: Mysterium.
%% 通用的PDA模拟
accept(L) :- parser(q,L).
parser(State,L) :-
trans(State,[],[]) :- final(State).start(State),
trans(State,L,[]).
trans(State,L,S) :-
delta(State,[],[],Next,Top),
append(Top,S,NewStack),
trans(Next,L,NewStack).
trans(State,L,[T|R]) :-
delta(State,[],T,Next,Top),
append(Top,R,NewStack),
trans(Next,L,NewStack).
trans(State,[L|R],S) :-
delta(State,L,[],Next,Top),
append(Top,S,NewStack),
trans(Next,R,NewStack).
trans(State,[L|R],[T|S]) :-
delta(State,L,T,Next,Top),
append(Top,S,NewStack),
trans(Next,R,NewStack).
%%%针对示例:起止状态和生成回文的转移函数:
start(q).
final(p).
delta(q,[],[],p,[sym_S]).
delta(p,[],sym_S,p,[a,sym_S,a]).
delta(p,[],sym_S,p,[b,sym_S,b]).
delta(p,a,a,p,[]).
delta(p,b,b,p,[]).
delta(p,[],sym_S,p,[]).
delta(p,[],sym_S,p,[a]).
delta(p,[],sym_S,p,[b]).
%% end of code