[ create a new paste ] login | about

Link: http://codepad.org/h1BF7bTf    [ raw code | output | fork ]

aaronla - Lua, pasted on Nov 28:
function memoize(f)
  store = {}
  function anon(x)
    if store[x] then
      return store[x]
    else
      y = f(x)
      store[x] = y
      return y
    end
  end
  return anon
end

invoked_count = 0

function fib(x)
  invoked_count = invoked_count + 1
  if x < 2 then
    return 1
  else
    return fib(x-1) + fib(x-2)
  end
end

fib = memoize(fib)

fib(10)
print("invoked_count = " .. invoked_count)


Output:
1
invoked_count = 11


Create a new paste based on this one


Comments: