繁体   English   中英

简单递归 function - OCAML

[英]Simple recursive function - OCAML

有人可以看看我的代码有什么问题吗? 它一直告诉我它会导致堆栈溢出。

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 优先级和关联性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM