本文介绍了f#stackoverflow项目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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 03:32