作为一个纯粹的学术练习,我从头开始编写一个递归下降解析器 - 不使用ANTLR或lex/yacc.
我正在写一个简单的函数,它将数学表达式转换为它们的等效AST.我有以下内容:
// grammar
type expr =
| Lit of float
| Add of expr * expr
| Mul of expr * expr
| Div of expr * expr
| Sub of expr * expr
// tokens
type tokens =
| Num of float
| LParen | RParen
| XPlus | XStar | XMinus | XSlash
let tokenize (input : string) =
Regex.Matches(input.Replace(" ", ""), "\d+|[+/*\-()]")
|> Seq.cast<Match>
|> Seq.map (fun x -> x.Value)
|> Seq.map (function
| …Run Code Online (Sandbox Code Playgroud)