gpt4 book ai didi

f# - 使用 Continuation Monad 的 100000 阶乘有什么问题?

转载 作者:行者123 更新时间:2023-12-01 07:26:46 25 4
gpt4 key购买 nike

它是使用递归的强大技术,因为它具有强大的可描述特性。尾递归提供了比普通递归更强大的计算能力,因为它将递归变成了迭代。 Continuation-Passing Style (CPS) 可以将很多循环代码变成尾递归。 Continuation Monad 提供递归语法,但本质上它是尾递归,也就是迭代。应该合理使用 Continuation Monad 进行 100000 阶乘。这是代码。

type ContinuationBuilder() =
member b.Bind(x, f) = fun k -> x (fun x -> f x k)
member b.Return x = fun k -> k x
member b.ReturnFrom x = x
(*
type ContinuationBuilder =
class
new : unit -> ContinuationBuilder
member Bind : x:(('d -> 'e) -> 'f) * f:('d -> 'g -> 'e) -> ('g -> 'f)
member Return : x:'b -> (('b -> 'c) -> 'c)
member ReturnFrom : x:'a -> 'a
end
*)
let cont = ContinuationBuilder()
//val cont : ContinuationBuilder
let fac n =
let rec loop n =
cont {
match n with
| n when n = 0I -> return 1I
| _ -> let! x = fun f -> f n
let! y = loop (n - 1I)
return x * y
}
loop n (fun x -> x)

let x2 = fac 100000I

有错误消息:“进程因 StackOverflowException 而终止。”

使用 ContinuationMonad 的 100000 阶乘有什么问题?

最佳答案

您需要在 Release模式下编译项目或检查项目属性中的“生成尾调用”选项(如果您通过命令行运行编译器,则使用 --tailcalls+)。

默认情况下, Debug模式下不启用尾调用优化。原因是,如果启用尾调用,您将看不到有关堆栈跟踪的有用信息。因此,默认禁用它们会给您带来更愉快的调试体验(即使在 Debug模式下,编译器也会优化调用自身的尾递归函数,它可以处理大多数情况)。

关于f# - 使用 Continuation Monad 的 100000 阶乘有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com