如何在Haskell中构建Parser [英] How to build Parser in Haskell

查看:138
本文介绍了如何在Haskell中构建Parser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  data Expr = ExprNum Double  - 常量
| ExprVar字符串 - 变量
| ExprAdd Expr Expr
| ExprSub Expr Expr
| ExprNeg Expr - 一元' - '操作符
| ExprMul Expr Expr
| ExprDiv Expr Expr
导出显示

这是我的用户自定义数据类型。我想使用上面的数据类型来处理像(2 + 3 * 4-x)这样的算术表达式,而不使用 buildExpression 解析器。我能做什么?

请帮助我,它应该处理操作符优先级。假设我们要构建一个 addsub 级别的分析器。 我们希望这样说(忽略实际返回正确的值并只关注原始解析)

  addsub = muldiv> ;> oneOf+  - >> muldiv 

这不起作用。但我们可以将这个因素留作

  addsub = muldiv>> addsub'
addsub'=许多$ oneOf+ - >> muldiv

我们假设 muldiv 是一个解析器仅仅是乘法和除法,你可以用类似的方式写出来。



也就是说,不是使用语法

  addsub = addsub(+  - )muldiv | muldiv 

我们使用的稍微复杂一点,但Parsec实际可用:

  addsub = muldiv addsub'
addsub'=(+ - )muldiv addsub'| Nothing

我们当然可以将后者重构为许多它给了我们一个我们要添加的表达式列表。然后,您可以将其转换为任何您想要的形式,例如(Add a1(Add a2(Add a3)))


data Expr   = ExprNum Double -- constants
            | ExprVar String -- variables
            | ExprAdd Expr Expr
            | ExprSub Expr Expr
            | ExprNeg Expr -- The unary '-' operator
            | ExprMul Expr Expr
            | ExprDiv Expr Expr
            deriving Show

This is my user define data type. I want to handle arithmetic expression like (2+3 *4 - x) using above data types without using buildExpression parser. What can I do?

Please help me.It should handle operator precedence.

解决方案

Suppose we want to build an addsub level parser. We'd like to say that (ignoring actual returning of correct values and just focusing on the raw parsing)

addsub = muldiv >> oneOf "+-" >> muldiv

This doesn't really work. But we can left factor this as

addsub = muldiv >> addsub'
addsub' = many $ oneOf "+-" >> muldiv

Where we assume muldiv is a parser for just multiplication and division which you can write in a similar manner.

That is, instead of using the grammar

addsub = addsub (+-) muldiv | muldiv

We use the slightly more complicated, but actually usable by Parsec:

addsub = muldiv addsub'
addsub' = (+-) muldiv addsub' | Nothing

Which we can of course refactor the latter into a many which gives us a list of expressions that we would add. You could then convert that to whatever form you want, such as (Add a1 (Add a2 (Add a3))).

这篇关于如何在Haskell中构建Parser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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