[英]Parsing function in haskell
I'm new to Haskell and I am trying to parse expressions. 我是Haskell的新手,我正在尝试解析表达式。 I found out about Parsec and I also found some articles but I don't seem to understand what I have to do. 我发现了Parsec,我也发现了一些文章,但我似乎不明白我必须做什么。 My problem is that I want to give an expression like "x^2+2*x+3" and the result to be a function that takes an argument x and returns a value. 我的问题是我想给出一个像“x ^ 2 + 2 * x + 3”这样的表达式,结果是一个带参数x并返回一个值的函数。 I am very sorry if this is an easy question but I really need some help. 如果这是一个简单的问题,我很抱歉,但我真的需要一些帮助。 Thanks! 谢谢! The code I inserted is from the article that you can find on this link . 我插入的代码来自您可以在此链接上找到的文章。
import Control.Monad(liftM)
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Token
import Text.ParserCombinators.Parsec.Language
data Expr = Num Int | Var String | Add Expr Expr
| Sub Expr Expr | Mul Expr Expr | Div Expr Expr
| Pow Expr Expr
deriving Show
expr :: Parser Expr
expr = buildExpressionParser table factor
<?> "expression"
table = [[op "^" Pow AssocRight],
[op "*" Mul AssocLeft, op "/" Div AssocLeft],
[op "+" Add AssocLeft, op "-" Sub AssocLeft]]
where
op s f assoc
= Infix (do{ string s; return f}) assoc
factor = do{ char '('
; x <- expr
; char ')'
; return x}
<|> number
<|> variable
<?> "simple expression"
number :: Parser Expr
number = do{ ds<- many1 digit
; return (Num (read ds))}
<?> "number"
variable :: Parser Expr
variable = do{ ds<- many1 letter
; return (Var ds)}
<?> "variable"
This is just a parser for expressions with variables. 这只是带变量的表达式的解析器。 Actually interpreting the expression is an entirely separate matter. 实际上,解释表达是一个完全独立的问题。
You should create a function that takes an already parsed expression and values for variables, and returns the result of evaluating the expression. 您应该创建一个函数,该函数接受已经解析的表达式和变量值,并返回计算表达式的结果。 Pseudocode: 伪代码:
evaluate :: Expr -> Map String Int -> Int
evaluate (Num n) _ = n
evaluate (Var x) vars = {- Look up the value of x in vars -}
evaluate (Plus e f) vars = {- Evaluate e and f, and return their sum -}
...
I've deliberately omitted some details; 我故意省略了一些细节; hopefully by exploring the missing parts, you learn more about Haskell. 希望通过探索缺失的部分,您可以了解有关Haskell的更多信息。
As a next step, you should probably look at the Reader
monad for a convenient way to pass the variable map vars
around, and using Maybe
or Error
to signal errors, eg referencing a variable that is not bound in vars
, or division by zero. 下一步,您应该查看Reader
monad,以便方便地传递变量map vars
,并使用Maybe
或Error
来表示错误,例如引用未绑定在vars
中的vars
,或者除以零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.