sách gpt4 ai đã đi

Phân tích cú pháp ứng dụng hàm bằng OperatorPrecedenceParser sử dụng FParsec?

In lại 作者:行者123 更新时间:2023-12-04 12:12:01 28 4
mua khóa gpt4 Nike

问题类似于this one ,但我想使用 OperatorPrecedenceParser 解析带有函数应用程序的表达式在 FParsec .

这是我的 AST:

type Expression =
| Float of float
| Variable of VarIdentifier
| BinaryOperation of Operator * Expression * Expression
| FunctionCall of VarIdentifier (*fun name*) * Expression list (*arguments*)

我有以下输入:
board→create_obstacle(4, 4, 450, 0, fric)

这是解析器代码:
let expr = (number |>> Float) <|> (ident |>> Variable)
let parenexpr = between (str_ws "(") (str_ws ")") expr

let opp = new OperatorPrecedenceParser<_,_,_>()

opp.TermParser <- expr <|> parenexpr

opp.AddOperator(InfixOperator("→", ws,
10, Associativity.Right,
fun left right -> BinaryOperation(Arrow, left, right)))

我的问题是函数参数也是表达式(它们可以包括运算符、变量等),我不知道如何扩展我的 biểu thức解析器将参数列表解析为表达式列表。我在这里构建了一个解析器,但我不知道如何将它与我现有的解析器结合起来:
let primitive = expr <|> parenexpr
let argList = sepBy primitive (str_ws ",")
let fcall = tuple2 ident (between (str_ws "(") (str_ws ")") argList)

我目前的解析器有以下输出:
Success: Expression (BinaryOperation 
(Arrow,Variable "board",Variable "create_obstacle"))

我想要的是获得以下内容:
 Success: Expression 
(BinaryOperation
(Arrow,
Variable "board",
Function (VarIdentifier "create_obstacle",
[Float 4, Float 4, Float 450, Float 0, Variable "fric"]))

1 Câu trả lời

您可以将参数列表解析为标识符的可选后缀表达式

let argListInParens = between (str_ws "(") (str_ws ")") argList
let identWithOptArgs =
pipe2 ident (opt argListInParens)
(fun id optArgs -> match optArgs with
| Some args -> FunctionCall(id, args)
| None -> Variable(id))

然后定义 biểu thức喜欢
let expr = (number |>> Float) <|> identWithOptArgs

关于使用 OperatorPrecedenceParser 使用 FParsec 解析函数应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9197687/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com