解析"x y z".优先于乘法 [英] Parsing "x y z" with the precedence of multiply
问题描述
我正在尝试使用FParsec为F#编写Mathematica语言的解析器.
I'm trying to write a parser for the Mathematica language in F# using FParsec.
我为MiniML写了一篇,它支持语法f x y = (f(x))(y)
,对于函数应用程序具有较高的优先级.现在,我需要使用相同的语法来表示f*x*y
,因此,其优先级与乘法相同.特别是x y + 2 = x*y + 2
而x y ^ 2 = x * y^2
.
I have written one for a MiniML that supports the syntax f x y = (f(x))(y)
with high precedence for function application. Now I need to use the same syntax to mean f*x*y
and, therefore, have the same precedence as multiply. In particular, x y + 2 = x*y + 2
whereas x y ^ 2 = x * y^2
.
这怎么完成?
推荐答案
正如Stephan在评论中指出的那样,您可以将运算符解析器拆分为两个单独的解析器,并将自己的解析器放在中间以使用空格分隔的表达式.以下代码演示了这一点:
As Stephan pointed out in a comment you can split the operator parser into two separate parsers and put your own parser in the middle for space-separated expressions. The following code demonstrates this:
#I "../packages/FParsec.1.0.1/lib/net40-client"
#r "FParsec"
#r "FParsecCS"
open FParsec
open System.Numerics
type Expr =
| Int of BigInteger
| Add of Expr * Expr
| Mul of Expr * Expr
| Pow of Expr * Expr
let str s = pstring s >>. spaces
let pInt : Parser<_, unit> = many1Satisfy isDigit |>> BigInteger.Parse .>> spaces
let high = OperatorPrecedenceParser<Expr,unit,unit>()
let low = OperatorPrecedenceParser<Expr,unit,unit>()
let pHighExpr = high.ExpressionParser .>> spaces
let pLowExpr = low.ExpressionParser .>> spaces
high.TermParser <-
choice
[ pInt |>> Int
between (str "(") (str ")") pLowExpr ]
low.TermParser <-
many1 pHighExpr |>> (function [f] -> f | fs -> List.reduce (fun f g -> Mul(f, g)) fs) .>> spaces
low.AddOperator(InfixOperator("+", spaces, 10, Associativity.Left, fun f g -> Add(f, g)))
high.AddOperator(InfixOperator("^", spaces, 20, Associativity.Right, fun f g -> Pow(f, g)))
run (spaces >>. pLowExpr .>> eof) "1 2 + 3 4 ^ 5 6"
输出为:
Add (Mul (Int 1,Int 2),Mul (Mul (Int 3,Pow (Int 4,Int 5)),Int 6))
按预期代表1 * 2 + 3 * 4^5 * 6
.
这篇关于解析"x y z".优先于乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!