Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
Overly Excessive Avatar asked Sep 29 '22 00:09

Overly Excessive


1 Answers

Yes, it's called "Tail Call Optimization" See here: http://blogs.msdn.com/b/chrsmith/archive/2008/08/07/understanding-tail-recursion.aspx Also Seq is lazy so its 500th member will not be evaluated until you will not have to access it in your program like:

let elm = Seq.nth 500 fibSeq
like image 198
Petr Avatar answered Oct 04 '22 04:10

Petr