【发布时间】:2021-07-11 12:07:28
【问题描述】:
我正在使用 FParsec 库为伪语言编写解析器, 我有一个语句解析器,它是所有可能的语句之间的选择 一个块解析器,它解析一系列语句,直到一个“结束”关键字 现在我想写一个“循环”结构,问题是,循环本身是一个语句,并且包含一个块 这导致了 F# 不喜欢的递归形式的定义 不久前我用 C# 编写了一个解析器,并且通过这个很容易,因为每个解析器都是一个函数,它们可以相互调用,而不管它们是在之前还是之后定义的
所以我想知道如何在 F# 中解决这个问题
这里是提到的解析器:
// parses a list of statements, separated by 1 or more newlines, (pre|post)fixed by any amount of whitespace, and finishes parsing upon reaching an "end" keyword
let block endtag = many1Till (statement .>> nl) (skipString endtag) // at this moment, statement is undefined
// parses a loop structure; the keyword loop, followed by an identifier for the iteration variable, followed by an expression which evaluates to the amount iterations which should be executed, followed by a block closed with "endloop"
let loop = skipString "loop" >>. ws1 >>. id .>> ws1 .>>. expr .>> nl .>>. block "endloop" |>> fun ((i, n), s) -> Loop (i, n, s)
// parses any statement, pre or post fixed by any amount of whitespace
let statement = spaces >>. choice [writeline; write; comment; definition; loop; sleep; assignment] .>> spaces
【问题讨论】:
标签: functional-programming f# fparsec