Consider the following Haskell code for computing the nth Fibonacci number.
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
This code is slow. We can optimize it by refactoring to a helper function that computes "iteratively", by "storing" all the relevant data to compute the recurrence with in its arguments, along with a "counter" that tells us how long to compute for.
fastfib :: Int -> Int
fastfib n = helper 1 0 n
where
helper a _ 1 = a
helper a b i = helper (a + b) a (i - 1)
It seems like this optimization could apply more broadly as well. Does it have a name, in the functional programming community or elsewhere?