Lua: Lazy Map Implementation: Round One


/ Published in: Lua
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require "std.table" -- For memoize
  2.  
  3. function map(t, f)
  4. local nt = table.memoize(function (k) return f(t[k]) end)
  5. local mt = getmetatable(nt)
  6. function mt:__pairs()
  7. local k
  8. local function mynext()
  9. k,v = next(t, k)
  10. if k == nil then return nil end
  11. return k,nt[k]
  12. end
  13. return mynext, self
  14. end
  15. return nt
  16. end
  17. require "std.base" -- For better table tostring()
  18.  
  19. local mylist = {1,3,5,7,9}
  20. local newlist = map(mylist, function(v) return 3 * v - 2 end)
  21. assert(mylist[3] == 5)
  22. assert(newlist[3] == 13)
  23.  
  24. require "std.base" -- For the pairs() that obeys the __pairs metamethod
  25. print("old:", mylist)
  26. print("new(3*v-2):", newlist)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.