简体   繁体   English

Prolog程序识别上下文无关文法a ^ nb ^ n

[英]Prolog program to recognize context free grammar a^n b^n

Using Prolog I'm trying to write a predicate that recognizes context free grammar and returns true if the input list matches the CFG . 我使用Prolog尝试编写一个可识别上下文无关语法谓词, 如果输入列表与CFG匹配,则返回true
The alphabet of the input consists only of a,b . 输入的字母仅包含a,b The CFG i'm trying to match is 我要匹配的CFG是

S-> TT
T -> aTb | ab

I'm not quite sure how to implement this, mainly the T rule. 我不太确定该如何实施,主要是T规则。

s(S0,S):-t(S0,S),t(S1,S).
t(S0,S):-S0 = a, t(S1,S), S1 = b; S0 = a, S1 = b.

match([H|T] :- s(H,T).

So if I query [a, a, b, b] it should return true . 因此,如果我查询[a, a, b, b]它应该返回true However, I'm just getting an infinite loop. 但是,我只是陷入无限循环。 I'm not quite sure how to implement the a^nb^n rule. 我不太确定如何实施a^nb^n规则。

I would write the CFG in this way: 我将以这种方式编写CFG:

S -> T
T -> a T b | {epsilon}

that translates directly to a DCG: 直接转换为DCG:

s --> t.
t --> [].
t --> a, t, b.

Note I swapped the epsilon rule, to get the ability to generate phrases. 注意我交换了epsilon规则,以获得生成短语的能力。

Translating that DCG by hand : 手动翻译该DCG:

s(S0,S) :- t(S0,S).
t(S0,S0).
t(S0,S) :- S0=[a|S1], t(S1,S2), S2=[b|S].

Yields 产量

?- phrase(s,L).
L = [] ;
L = [a, b] ;
L = [a, a, b, b] ;
L = [a, a, a, b, b, b] ;
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM