Reputation: 57
Can someone take a look at what is wrong with my code? It keeps telling me that it will cause stack overflow.
let rec to_ten x =
if x = 10 then x
else if x < 10 then to_ten x + 1
else to_ten x - 1
;;
Upvotes: 1
Views: 70
Reputation: 38789
Here you need to add parentheses around addition and subtraction:
let rec to_ten x =
if x = 10 then x
else if x < 10 then to_ten (x + 1)
else to_ten (x - 1)
Otherwise, operator precedence makes to_ten x + 1
read as ((to_ten x) + 1)
, which results in an infinite loop. See 7.7.1 Precedence and associativity
Upvotes: 2