Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Lua: Lazy Map Implementation: Round One (See related posts)

Concept code for a lazy map implementation in Lua

require "std.table" -- For memoize

function map(t, f)
    local nt = table.memoize(function (k) return f(t[k]) end)
    local mt = getmetatable(nt)
    function mt:__pairs()
        local k
        local function mynext()
            k,v = next(t, k)
            if k == nil then return nil end
            return k,nt[k]
        end
        return mynext, self
    end
    return nt
end


Example Usage:
require "std.base" -- For better table tostring()

local mylist = {1,3,5,7,9}
local newlist = map(mylist, function(v) return 3 * v - 2 end)
assert(mylist[3] == 5)
assert(newlist[3] == 13)

require "std.base" -- For the pairs() that obeys the __pairs metamethod
print("old:", mylist)
print("new(3*v-2):", newlist)

You need to create an account or log in to post comments to this site.


Click here to browse all 4848 code snippets

Related Posts