简体   繁体   中英

Stack overflows and recursive sequence expressions F#

I have a sequence expression like so:

let fibSeq = 
    let rec fibSeq' a b = 
        seq { yield a
              yield! fibSeq' b (a + b) }
    fibSeq' 1 1

Now even for large numbers, this will not generate a stack overflow. I'm wondering why, it seems to me that to generate n Fibonacci numbers with this sequence expression each recursive call would need to return back to the caller eventually to "fold" itself into the sequence. Is there some sort of optimization going on behind the scenes here?

是的,它被称为“尾调用优化”请参见: http//blogs.msdn.com/b/chrsmith/archive/2008/08/07/understanding-tail-recursion.aspx此外,Seq很懒,所以它的第500个成员将在您不必在程序中访问它之前不要进行评估,例如:

let elm = Seq.nth 500 fibSeq

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