为什么解析器组合器“seq”用“结合”定义。和“返回”? [英] Why is parser combinator "seq" defined with "bind" and "return"?

查看:100
本文介绍了为什么解析器组合器“seq”用“结合”定义。和“返回”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于解析器组合器的文章,而没有理解以下内容:

他们说使用 seq (见下文)会导致带有嵌套元组的解析器作为结果,这是操作凌乱

  seq :: Parser a  - >解析器b  - >解析器(a,b)
p'seq'q = \inp - > [((v,w),inp'')| (v,inp')<-p inp,(w,inp'')<-q inp']

为了避免嵌套元组的问题,他们引入了 monadic bind return 解析器,然后定义 seq ,如下所示:

  p'seq'q = p'bind'\x  - > q'bind'\y  - >结果(x,y)

不幸的是我没有看到嵌套元组的问题是为什么 seq 的第二个实现比第一个更好。你可以帮我理解它吗?

解决方案

第一个示例扩展为类型((a,b),(c, (p,q),(r,s,t)= \inp - (p,q) >
[(((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''''
]

  seq232((p,q),(r,s,t))= 
p'bind'\v - >
q'bind'\\ \\ w - >
r`bind` \x - >
s`bind` \y - >
t`bind` \z - >
result( (x,y,z))
<很多更好,我想你可以看到第二个是更清洁。


I am reading this article about parser combinators and didn't understand the following:

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’]

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)

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?

解决方案

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''''
     ]

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.

这篇关于为什么解析器组合器“seq”用“结合”定义。和“返回”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆