【问题标题】:Simple recursive function - OCAML简单的递归函数 - OCAML
【发布时间】: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
  ;;

【问题讨论】:

    标签: recursion ocaml


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2021-11-28
      • 2013-02-23
      相关资源
      最近更新 更多