f# stackoverflow 项目 euler #4 [英] f# stackoverflow project euler #4
问题描述
我正在处理 Project Euler 的问题四,并且遇到了 stackoverflow 异常.我不是在寻求解决问题的帮助,我只是想解释为什么我遇到了stackoverflow异常.这通常是因为无限递归,但我不相信这次是这种情况(如果我只是瞎了,现在没看到,请告诉我).
I'm working on problem four of Project Euler and am running into a stackoverflow exception. I'm not asking for help on solving the problem, I'd just like it explained why I am getting a stackoverflow exception. It's usually because of infinite recursion but I don't believe that is the case this time (if I'm just blind and not seeing it right now please let me know).
代码如下:
let Euler4 =
let reverse sum =
let rec loop (n,x) =
if n = 0
then
x
else
loop (n/10,(x*10) + (n%10))
loop (sum, 0);
let isPalindrome arg = (arg = (reverse arg));
let findPalindromes (startx,starty) =
let rec loop (x,y) acc =
let result = if isPalindrome (x * y) then ((x,y) :: acc) else acc;
let next = match (x,y) with
| (x,y) when y = 100 -> (x-1,starty)
| _ -> (x,y-1)
if x = 100 then
result
else
loop (next) result
loop (startx,starty) [];
let value = (999,999);
printfn "%A" (findPalindromes value);
;
推荐答案
您是在调试"模式还是发布"模式下编译?VS 中的调试模式默认关闭尾调用(编译器标志--tailcalls-"),以保留用于调试的堆栈,但这需要权衡 StackOverflow.您可以切换到发布"模式,或者
Are you compiling in 'Debug' mode or 'Release' mode? Debug mode in VS has tail calls turned off by default (compiler flag "--tailcalls-"), in order to preserve stacks for debugging, but this has the trade-off that you may StackOverflow. You can either switch to 'Release' mode, or
- 右键单击解决方案资源管理器中的项目属性,选择属性"
- 转到构建"标签
- 确保选择了调试"配置
- 点击生成尾调用"框
使用调试"设置打开尾调用.
to turn on tail calls with 'Debug' settings.
(你的程序在启用尾调用的情况下运行良好.)
(Your program runs fine for me with tail calls enabled.)
这篇关于f# stackoverflow 项目 euler #4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!