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:05

>>16
Now with more loeb!

import Control.Applicative

loeb :: Functor f => f (f a -> a) -> f a
loeb x = ($ loeb x) <$> x

fib :: Int -> Integer
fib = (fibs!!)
  where fibs = loeb $ const 0 : const 1 : map (\n xs -> xs !! (n - 2) + xs !! (n - 1)) [2..]

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