问题描述
我正在阅读有关解析器组合器的文章,但没有了解以下内容:
I am reading this article about parser combinators and didn't understand the following:
他们说,使用 seq
(见下文)导致解析器将嵌套元组作为结果,操作起来很麻烦.
They say that using seq
(see below) leads to parsers with nested tuples as results, which are messy to manipulate.
seq :: Parser a -> Parser b -> Parser (a,b)
p ‘seq‘ q = \inp -> [((v,w),inp’’) | (v,inp’) <- p inp, (w,inp’’) <- q inp’]
为了避免嵌套元组的这种问题,他们引入了 monadic bind
和 return
进行解析,然后定义 seq
如下:
In order to avoid this problem of nested tuples they introduce monadic bind
and return
for parsers and then define seq
as follows:
p ‘seq‘ q = p ‘bind‘ \x -> q ‘bind‘ \y -> result (x,y)
不幸的是,我看不到嵌套元组的问题是什么,为什么 seq
的第二个实现比第一个更好.你能帮我理解吗?
Unfortunately I don not see what the problem of nested tuples is and why the 2-nd implementation of seq
is better then the 1-st one. Could you help me to understand it?
推荐答案
第一个示例扩展到类型((a,b),(c,d,e)):
The first example extendend to the type ((a,b),(c,d,e)):
seq232 ((p,q),(r,s,t) = \inp ->
[ (((v,w),(x,y,z)),inp’’''')
| (v, inp’) <- p inp
, (w, inp’’) <- q inp’
, (x, inp''') <- r inp''
, (y, inp'''') <- s inp'''
, (z, inp''''') <- t imp''''
]
第二个示例扩展为类型((a,b),(c,d,e)):
The second example extended to the type ((a,b),(c,d,e)):
seq232 ((p,q),(r,s,t)) =
p ‘bind‘ \v ->
q ‘bind‘ \w ->
r `bind` \x ->
s `bind` \y ->
t `bind` \z ->
result ((v,w),(x,y,z))
虽然不是很多 更好,但我认为您可以看到第二个更加干净.
While it isn't a a lot better, I think you can see that the second is a bit cleaner.
这篇关于为什么解析器组合器& quot; seq&"会出现错误.用&" bind&"定义和“返回"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!