Prolog 问题 - 简单语法实现
如果我有以下语法:
S → ε
S → a S b S
如何在 Prolog 中实现它?
我尝试了这个:
isMatched([]).
isMatched([a,b]).
isMatched([a|[S1|[b|S2]]]) :- isMatched(S1), isMatched(S2).
但它显然不起作用,因为列表的头部不能是列表。
然后我尝试实现一个新版本,如下所示:
conc([], R, R).
conc([H|T], L, [H|R]) :- conc(T, L, R).
isMatched([]).
isMatched([a,b]).
isMatched(List) :- conc([a], S1, List3), isMatched(S1), conc(List3, [b], List2), conc(List2, S2, List), isMatched(S2).
但是对于输入 isMatched([a,b,a]) ,它耗尽了堆栈。
如何解决这个问题?
If I have the following grammar:
S → ε
S → a S b S
How do I implement it in Prolog?
I tried this:
isMatched([]).
isMatched([a,b]).
isMatched([a|[S1|[b|S2]]]) :- isMatched(S1), isMatched(S2).
But it obviously doesn't work because the head of a list cannot be a list.
I then tried implementing a new version as follows:
conc([], R, R).
conc([H|T], L, [H|R]) :- conc(T, L, R).
isMatched([]).
isMatched([a,b]).
isMatched(List) :- conc([a], S1, List3), isMatched(S1), conc(List3, [b], List2), conc(List2, S2, List), isMatched(S2).
But for the input isMatched([a,b,a])
, it runs out of stack.
How do I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来像是家庭作业,所以我不会尝试为你做。
您可能想看看 Prolog 中的定语子句语法 (DCG)。这基本上是语法糖,允许您编写读起来更像语法而不是 Prolog 谓词的语法。如果您了解它们是如何工作的,那么您可能会对如何在 Prolog 中进行解析有一个很好的理解。
Sounds like homework, so I won't try and do it for you.
You might want to take a look at definite clause grammars (DCGs) in Prolog. This is basically syntactic sugar that allows you to write grammars that read more like grammars than Prolog predicates. If you understand how these work, then you'll probably have a decent understanding of how to parse in Prolog.