我正在尝试使用 FParsec 在 F# 中为 Mathematica 语言编写解析器。
我为 MiniML 编写了一个,它支持f x y = (f(x))(y)
函数应用的高优先级语法。现在我需要使用相同的语法来表示f*x*y
,因此具有与乘法相同的优先级。特别是,x y + 2 = x*y + 2
而x y ^ 2 = x * y^2
.
如何实现?
正如 Stephan 在评论中指出的那样,您可以将运算符解析器拆分为两个单独的解析器,并将您自己的解析器放在中间用于空格分隔的表达式。下面的代码演示了这一点:
#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
了预期。