递归计算表达式

发布于 2024-09-09 04:49:45 字数 1998 浏览 12 评论 0原文

上一个问题中,我被告知如何重写我的计算表达式,以便它使用尾递归。我重写了代码,但仍然遇到 StackOverflowException。为了找到问题,我使用状态 monad 编写了一些小代码(取自 此博客条目):

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

In a previous question I was told how to rewrite my computation expressions so it uses tail recursion. I rewrote my code but still got a StackOverflowException. To locate the problem I wrote some small code using a state monad (taken from 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

This is throwing a StackOverflowException again, although the Loop function could use tail recursion(?). I guess something is wrong with the StateBuilder class. I tried to do something with the Delay method. Wraping everything in an extra lambda, without success.
Im totally stucked at the moment. Here my second attempt (does not compile):

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静赏你的温柔 2024-09-16 04:49:45

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

在调试模式下默认禁用尾部调用的原因是,它使调试变得更加困难(如果调用作为尾部调用执行,您将不会在调用堆栈中看到它 em> window)

这将是一个非常愚蠢的错误原因...抱歉,当您之前询问时我忘记提及这一点!

I'm afraid that you may be getting StackOverflowException because you're running the program in Debug mode with disabled tail-call generation. If you go to Project properties, then you can find Generate tail calls checkbox on the Build tab. When I create a new project, I can reproduce the behavior, but after checking this option, it works fine (even for much larger number of iterations).

The reason why tail-calls are disabled by default in the Debug mode is that it makes debugging a lot more difficult (if a call is performed as a tail-call, you wouldn't see it in the Call Stack window)

This would be a pretty silly reason for the error... sorry that I forgot to mention this when you asked earlier!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文