Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

f# stackoverflow project euler #4

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).

Here's the code:

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);

;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  • right-click the project properties in Solution Explorer, select 'Properties'
  • go to the 'Build' tab
  • make sure 'Debug' configuration is selected
  • click the box 'Generate tail calls'

to turn on tail calls with 'Debug' settings.

(Your program runs fine for me with tail calls enabled.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...