Lamebro1
Lamebro1

Reputation: 57

Simple recursive function - OCAML

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

Answers (1)

coredump
coredump

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

Related Questions