简体   繁体   English

F#递归函数参数和堆栈溢出

[英]F# recursive function arguments and stack overflow

I am somewhat new to F#, and I came across some strange behaviour when I was working with some recursive functions. 我对F#有些新鲜,当我使用一些递归函数时,我遇到了一些奇怪的行为。 I have two different versions of it below: 我有两个不同的版本:

Version 1: 版本1:
This causes a stack overflow, though it seems that it shouldn't (at least to my noob eyes) 这导致堆栈溢出,虽然它似乎不应该(至少对我的noob眼睛)

let rec iMake acc =
  match acc with
  | 10 -> 100
  | _ -> iMake acc+1

Version2: 版本2:
This one works as I would expect it to. 这个可以像我期望的那样工作。

let rec iMake acc =
  match acc with
  | 10 -> 100
  | _ -> iMake (acc+1)

The only difference is that version 2 puts the acc+1 expression into parenthesis. 唯一的区别是版本2将acc + 1表达式放入括号中。 So my question is, why does the first version not work, but the second one does? 所以我的问题是,为什么第一个版本不起作用,但第二个版本不起作用? Does this mean that I should put all of my function arguments into parenthesis to avoid this type of stuff in the future ? 这是否意味着我应该将所有函数参数放入括号中以避免将来出现这种类型的东西?

Function call has higher precedence than binary operator + . Function call优先级高于二元运算符+ So the first function actually works like: 所以第一个函数实际上就像:

let rec iMake acc =
    match acc with
    | 10 -> 100
    | _ -> (iMake acc)+1

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

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