我目前正在尝试使用 Petricek 和 Skeet 合着的 Real-World Functional Programming(2010 年)一书学习 f#,但在使用延续以避免堆栈溢出时遇到了问题。
我一直遇到的问题是,我使用延续的代码在 f# 交互中启动时运行良好,但在将代码放在 program.fs 文件中然后通过 Visual Studio 中的调试器启动它时仍然会导致堆栈溢出.
我不清楚为什么会这样,如果有人能给我解释为什么会这样,我将不胜感激。
如果 Visual Studio 的版本是相关的,我正在使用: Visual Studio 终极版 2012 版本 11.0.61030.00 更新 4
使用的 .Net 框架是: 版本。 4.5.51641
书中给出的导致这个问题的代码如下所示:
open System
let rand = new Random()
//A tree is either a leaf with a value or a node that contains two children
type IntTree =
| Leaf of int
| Node of IntTree * IntTree
//A list of that will decide all leaf values
let numbers2 = List.init 1000000 (fun _ -> rand.Next(-50,51))
///Creates an imbalanced tree with 1000001 leafs.
let imbalancedTree2 =
numbers2 |> List.fold (fun currentTree num ->
Node(Leaf(num), currentTree)) (Leaf(0))
//Sums all leafs in a tree by continuation and will execute the inserted function with the total
//sum as argument once all values have been summed.
let rec sumTreeCont tree cont =
match tree with
| Leaf(num) -> cont(num)
| Node(left, right) ->
sumTreeCont left (fun leftSum ->
sumTreeCont right (fun rightSum ->
cont(leftSum + rightSum)))
//Sums the imbalanced tree using the sumTreeCont function
let sumOfTree = sumTreeCont imbalancedTree2 (fun x -> x)
提前致谢! //老虎 Storm
最佳答案
如果您在 Debug模式下运行程序,则默认的 Visual Studio 项目设置会禁用尾调用。主要原因是,启用尾调用后,您无法在调用堆栈中获得非常有用的信息(这使得调试更加困难)。
要解决此问题,您可以转到项目选项并选中“构建”页面上的“生成尾调用”。在 Release模式下,这是默认启用的。
关于f# - 在 Visual Studio 中使用延续启动函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27334255/