[ create a new paste ] login | about

Link: http://codepad.org/OSzbA7Fl    [ 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

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

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


Output:
1
2
fib(10) = 89
invoked_count = 11


Create a new paste based on this one


Comments: