我编写了以下函数来检查括号表达式的有效性:
let matched str =
let rec matched' stack = function
| "" -> isEmpty stack
| str ->
match first str with
| '(' | '[' | '{' as p -> matched' (push p stack) (rest str)
| ')' -> matchClosing '(' stack str
| ']' -> matchClosing '[' stack str
| '}' -> matchClosing '{' stack str
| _ -> matched' stack (rest str)
and matchClosing expected stack s =
match peek stack with
| Some c when c = expected -> matched' (pop stack) (rest s)
| _ -> false
matched' [] str
如果我们替换matchClosing
into的实现matched'
,我们会得到一个尾递归函数。F# 编译器可以识别这一点并优化递归调用吗?