简体   繁体   中英

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. I have two different versions of it below:

Version 1:
This causes a stack overflow, though it seems that it shouldn't (at least to my noob eyes)

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

Version2:
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. 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 + . So the first function actually works like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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