简体   繁体   中英

how to call a function and use a global variable in that function

so my goal is to separate the following tail recursion function into two functions.

let fib (n:int) :int = 
    let rec loop (i:int) (a:int) (b:int) :int  =
        if i = n then a
        else loop (i+1) (b) (a+b) in 
    loop 0 0 1;;

I'm not sure how to use n in loop function.

You can't, that what makes nested function definitions so popular :-) You would need to add a fourth parameter, and pass that through all of your recursive calls unaltered:

let rec loop i n a b = 
  if i = n then a
  else loop (i+1) (n) (b) (a+b) 

let fib n = 
  loop 0 n 0 1

Alternatively, you change the looping structure so that it doesn't count i up from 0 to n , but rather have a variable (say j ) count down from n so you only need to check when it reaches 0 in loop :

let rec loop j a b = 
  if j = 0 then a
  else loop (j-1) (b) (a+b) 

let fib n = 
  loop n 0 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