gpt4 book ai didi

f# - 解析 if/else/if 语句

转载 作者:行者123 更新时间:2023-12-05 00:43:21 25 4
gpt4 key购买 nike

我试图复制一个简单的 if 语句的结构:

if (paren) { block } [else ({ block } | rec if (paren)) ]

对于 if (paren) 块,我创建了一个 IfBlock AST 节点。否则,它会递归地填充 IfElseBlock 节点。

我已经尝试了很多替代结构
let parse_if = 
suffixparen .>>. suffixblock |>> IfBlock
//>>? attempt (str "else" >>. ifParser) |>> IfElseBlock
//<|> preturn IfBlock
// .>>? attempt (str "else" >>. ifParser) |>> IfElseBlock
// suffixparen .>>. suffixblock |>> IfBlock
// <|> ifParser |>> IfElseBlock

let inlineIf = str_ws "if" >>. parse_if
do ifParserR := inlineIf

建议?

最佳答案

你有没有看过我的 GLSL 解析器(它是一种类似 C 的语言)?
http://laurent.le-brun.eu/fsharp/glsl_parse.fs

从代码示例中,这里是 if 的相关部分陈述:

let statement, stmtRef = createParserForwardedToRef()

let ifStatement =
pipe3 (keyword "if" >>. parenExp) statement (opt (keyword "else" >>. statement))
(fun cond stmt1 stmt2 -> Ast.If(cond, stmt1, stmt2))

stmtRef := choice [
simpleStatement
block
ifStatement
forLoop
//...
]

我认为您的问题是您正在使用 attempt而不是 opt . opt表示 else部分是可选的(如果它不存在,你会得到 None )。 attempt完全不同:

The parser attempt p applies the parser p. If p fails after changing the parser state or with a fatal error, attempt p will backtrack to the original parser state and report a non‐fatal error.



当解析器在 attempt失败,仍然有错误,但没有消耗输入(与 <|>choice 运算符结合使用时很有用)。

关于f# - 解析 if/else/if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6341288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com