递归计算表达式

时间:2010-07-09 19:25:11

标签: f# tail-recursion stack-overflow computation-expression

previous question中,我被告知如何重写我的计算表达式,因此它使用尾递归。我重写了我的代码,但仍然得到了StackOverflowException。为了找到问题,我使用状态monad(取自this blog entry)编写了一些小代码:

type State<'a, 's> = State of ('s -> 'a * 's)

let runState (State s) initialState = s initialState

let getState = State (fun s -> (s,s))
let putState s = State (fun _ -> ((),s))

type StateBuilder() =
  member this.Return a = State (fun s -> (a, s))
  member this.Bind(m, k) = 
    State (fun s -> let (a,s') = runState m s in runState (k a) s')
  member this.ReturnFrom a = a
let state = new StateBuilder()

let s max = 
    let rec Loop acc = state {
        let! n = getState
        do! putState (n + 1)
        if acc < max then
            return! Loop (acc + 1)
        else return acc
        }
    Loop 0

runState (s 100000) 0

这会再次抛出StackOverflowException,尽管Loop函数可以使用尾递归(?)。我想StateBuilder类有问题。我尝试用Delay方法做一些事情。在额外的lambda中扯掉一切,但没有成功。 我现在完全被困住了。这是我的第二次尝试(不编译):

type State<'a, 's> = State of ('s -> 'a * 's)

let runState (State s) initialState = s initialState

let getState = fun () -> State (fun s -> (s,s))
let putState s = fun () -> State (fun _ -> ((),s))

type StateBuilder() =
  member this.Delay(f) = fun () -> f()
  member this.Return a = State (fun s -> (a, s))
  member this.Bind(m, k) = 
    fun () -> State (fun s -> let (a,s') = runState (m ()) s in runState ((k a) ()) s')
  member this.ReturnFrom a = a
let state = new StateBuilder()

let s max = 
    let rec Loop acc = state {
        let! n = getState
        do! putState (n + 1 - acc)
        if acc < max then
            return! Loop (acc + 2)
        else return acc
        }
    Loop 0

runState (s 100000 ()) 0

1 个答案:

答案 0 :(得分:14)

我担心您可能会收到StackOverflowException,因为您在调试模式下运行程序并禁用尾部调用生成。如果您转到项目属性,则可以在 Build 选项卡上找到生成尾调用复选框。当我创建一个新项目时,我可以重现该行为,但在检查此选项后,它可以正常工作(即使迭代次数更多)。

默认情况下在调试模式下禁用尾调用的原因是它使调试变得更加困难(如果调用是作为尾调用执行的,则不会在调用中看到它堆栈窗口)

这对于错误来说是一个非常愚蠢的原因...对不起,我在你早些时候提出要求时忘记提及这一点了!