Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Closures are Fucking Awesome!

Name: Anonymous 2012-11-17 2:29

function newfibs()
    fibtable = {[0]=0, 1}
    function fibs (n)
        if fibtable[n] then
            return fibtable[n]
        else
            fibtable[n] = fibs(n -1) + fibs(n - 2)
            return fibtable[n]
        end
    end
    return fibs
end


> fibs=newfibs()
print(fibs(5))
5
print(fibs(20))
6765
print(fibs(50)) -- calculates instantaneously, unlike a naive recursive implementation
12586269025


I wrote this in like 30 seconds. A C equivalent that memoized previously calculated values in the Fibonacci sequence would have taken me several minutes to write. How did I ever get by without closures and tables?

Name: Anonymous 2012-11-17 22:59

>>18
It returns the element at the given index, so ['a','b','c'] !! 1 = 'b'. Also, (fibs !!) is a partial application - it's a function that given x, returns fibs !! x.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List