News for hackers. Stuff that matters.
Re:It Can Happen to You by desertrider12 on Thursday March 04, 2021 @12:22AM (#26338943)
This isn't really related to your question, but I don't think tail calls could help for Fibonacci since f(n) branches to two calls, f(n-1) and f(n-2). And each of those branches into 2. So it can't be done in a finite stack area with naive recursion.

The compiler would either have to memoize, or be extremely clever and start at the base case (0, 1) and then transform the code to use the 2x2 matrix exponentiation. I wouldn't have been suprised if GHC haskell was that clever, but even with -O2 "print $ fibb 10000" isn't terminating.

Re:It Can Happen to You by iamevn on Thursday March 04, 2021 @02:10AM (#26339554)
Wouldn't this be the recursion version with tail calls?

  (define/contract (fib n)
    (-> nonnegative-integer? nonnegative-integer?)
    (let fib-recur ([i 1] [curr 1] [prev 0])
      (cond [(= i n) curr]
            [else (fib-recur (+ i 1) 
                             (+ curr prev) 
                             curr)])))
Re:It Can Happen to You by desertrider12 on Thursday March 04, 2021 @09:36PM (#26351819)
That's pretty much what I meant by the matrix exponentiation method - applying the map (a, b) -> (a+b, a) repeatedly. Your function definitely uses tail calls, but I was just trying to say more than tail call optimization is needed to transform the trivial recursive version

fibb 0 = 0

fibb 1 = 1

fibb n = + (fibb (- n 1)) (fibb (- n 2))

into that, or any O(n) version.

Re:It Can Happen to You by kaba0 on Thursday March 04, 2021 @04:43AM (#26340477)
Haskell is not that clever (or at least it was not a year ago). The memoized version is much much faster.
Re:It Can Happen to You by adrianN on Thursday March 04, 2021 @01:18AM (#26339243)
If you replaced the recursion with loops but implemented the same algorithm you'd just have to manage a stack on the heap. I don't think that would be faster.