既然写了PDA Parser,干脆再写个TM Parser。
TM Parser 最麻烦的地方在于对整个TM的定义,就是An Example下面的部分。因此我只选了一个正则的简单语言来作为例子。
%%2013-01-28
%% Turing Machine Parser%% Author : Mysterium
%%% Turing machine parser
%%% sp means space
decide(W) :- parser(p,W,F),F == 1,!.
parser(State,[R|Rs],F) :-
trans(State,[R,sp,left_end_mark],Rs,F).
trans(State,_,_,F) :- acpt(State),F is 1.
trans(State,_,_,F) :- deny(State),F is 0.
trans(State,[L|Ls],[R|Rs],F) :-
delta(State,L,Next,move_right),
append([R],[L|Ls],NewL),
trans(Next,NewL,Rs,F).
trans(State,[L|Ls],R,F) :-
delta(State,L,Next,move_left),
trans(Next,Ls,[L|R],F).
trans(State,[L|Ls],R,F) :-
delta(State,L,Next,A),
alphabet(A),
trans(Next,[A|Ls],R,F).
trans(State,[left_end_mark|Ls],[R|Rs],F) :-
append([R],[left_end_mark|Ls],NewL),
trans(State,NewL,Rs,F).
%%% An Example
%%% 状态和转移关系定义:
%% 遇到a右移一格,遇到空格则no,遇到b则yes
%% 就是判断一个串中是否含有字母b
acpt(y).
deny(n).
alphabet(a).
alphabet(b).
delta(p,a,p,move_right).
delta(p,b,y,_).
delta(p,sp,n,_).
%% end of code
一些测试:
?- decide([a,a,a,a,b,sp,b]).
true.
?- decide([a,a,b,a]).
true.
?- decide([a,a,a,a,a,sp,b]).
false.
?- decide([a,a,a,a,a]).
false.