【发布时间】:2017-07-08 06:02:10
【问题描述】:
我正在尝试在树结构中建立一些规则,使用逻辑门,即 and、not、or 以及条件,例如属性 x 等于值 y。我先写了最明显的递归函数,它奏效了。然后,我从this post about generic tree folding 和this answer on stackoverflow 中得到提示,尝试编写一个不会导致堆栈溢出的连续传递样式。
它适用于小树(深度约为 1000),但不幸的是,当我使用 Xamarin Studio 在 Mac 上运行它时,使用大树时会导致堆栈溢出。谁能告诉我我是否误解了 F# 如何处理尾递归代码,或者这段代码是否不是尾递归?
let FoldTree andF orF notF leafV t data =
let rec Loop t cont =
match t with
| AndGate (left, right)->
Loop left (fun lacc ->
Loop right (fun racc ->
cont (andF lacc racc)))
| OrGate (left, right)->
Loop left (fun lacc ->
Loop right (fun racc ->
cont (orF lacc racc)))
| NotGate exp ->
Loop exp (fun acc -> cont (notF acc))
| EqualsExpression(property,value) -> cont (leafV (property,value))
Loop t id
let evaluateContinuationPassingStyle tree data =
FoldTree (&&) (||) (not) (fun (prop,value) -> data |> Map.find prop |> ((=) value)) tree data
【问题讨论】:
标签: recursion xamarin f# functional-programming stack-overflow