List Operations

lua-users home
wiki

Showing revision 2

[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. It does not run as is under Lua 5.

Lua's cunning syntactic sugar for using tables as lists is just waiting to be exploited... Many of these functions are unashamedly functional in flavour, and very useful, though if you're not a functional programmer you may take a while to get used to them.

-- Map a function over a list
function map(f, l)
  local m = {}
  for i = 1, getn(l) do m[i] = f(l[i]) end
  return m
end

-- Map a function over a list of lists
function mapCall(f, l)
  local m = {}
  for i = 1, getn(l) do m[i] = call(f, l[i]) end
  return m
end

-- Apply a function to each element of a list
function apply(f, l)
  for i = 1, getn(l) do f(l[i]) end
end

-- Execute the members of a list as assignments (assumes the keys are
-- strings)
function assign(l)
  foreach(l, function (i, v) setglobal(i, v) end)
end

-- Turn a table into a list of lists
function listify(t)
  local l = {}
  foreach(t, function (i, v) tinsert(%l, {i,v}) end)
  return l
end

-- Call a function with values from 1..n, returning a list of results
function loop(n, f)
  local l = {}
  for i = 1, n do tinsert(l, f(i)) end
  return l
end

-- Concatenate two lists and return the result
function concat(l, m)
  local n = {}
  foreachi(l, function (i, v) tinsert(%n, v) end)
  foreachi(m, function (i, v) tinsert(%n, v) end)
  return n
end

-- Reverse a list and return the result
function reverse(l)
  local m = {}
  for i = getn(l), 1, -1 do tinsert(m, l[i]) end
  return m
end

-- Zip some lists together with a function
function zipWith(f, ls)
  local m, len = {}, getn(ls)
  for i = 1, call(max, map(getn, ls)) do
    local t = {}
    for j = 1, len do tinsert(t, ls[j][i]) end
    tinsert(m, call(f, t))
  end
  return m
end

-- Transpose a matrix (can be used to do unzip)
function transpose(ls)
  local ms, len = {}, getn(ls)
  for i = 1, call(max, map(getn, ls)) do
    ms[i] = {}
    for j = 1, len do
      tinsert(ms[i], ls[j][i])
    end
  end
  return ms
end
zip = transpose
unzip = transpose

-- Project a list of fields from a list of records
--   l: list of records
--   f: field to project
-- returns
--   l: list of f fields
function project(l, f)
  local p = {}
  for i = 1, getn(l) do
    p[i] = l[i][f]
  end
  return p
end

-- Make an index for a list on the given field
function makeIndex(f, l)
  local ind = {}
  for i = 1, getn(l) do
    ind[l[i][f]] = i
  end
  return ind
end

RecentChanges · preferences
edit · history · current revision
Edited December 31, 2006 12:10 am GMT (diff)