【发布时间】:2019-11-21 02:40:47
【问题描述】:
有人可以看看我的代码有什么问题吗?它一直告诉我它会导致堆栈溢出。
let rec to_ten x =
if x = 10 then x
else if x < 10 then to_ten x + 1
else to_ten x - 1
;;
【问题讨论】:
有人可以看看我的代码有什么问题吗?它一直告诉我它会导致堆栈溢出。
let rec to_ten x =
if x = 10 then x
else if x < 10 then to_ten x + 1
else to_ten x - 1
;;
【问题讨论】:
这里需要在加减法两边加上括号:
let rec to_ten x =
if x = 10 then x
else if x < 10 then to_ten (x + 1)
else to_ten (x - 1)
否则,运算符优先级会使to_ten x + 1 读取为((to_ten x) + 1),从而导致无限循环。见7.7.1 Precedence and associativity
【讨论】: