2
let rec f a p n = if p n then a else a + f a p ( n - 1 )
let a, p, n = 3, ( fun x -> x = 1 ), 4
f a p n

Getting stackoverflow when n <= 0. Not sure how to get around this.

1
  • Trying to build rep here. Why the down vote? Commented Apr 26, 2013 at 18:18

1 Answer 1

4

Your p = fun x -> x = 1 which, of course, checks if x is 1.

Your recursive call uses p on n, otherwise decrements n.

This will cause n to become more and more negative, resulting in infinite recursion since n will never be 1. To solve this you need to not call p with a value of n less than 1 or change your check function to do something other than check for a value of 1.

Maybe try let a, p, n = 3, ( fun x -> x <= 1 ), 4.

Sign up to request clarification or add additional context in comments.

1 Comment

It's also worth noting that if f were made tail-recursive then the code would "work" (i.e. not crash) with p as-is, as n would eventually underflow and count down from Int32.Max to 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.