列表操作

lua-users home
wiki

[!] 版本说明: 以下代码适用于旧版本的 Lua,Lua 4。它在 Lua 5 下无法直接运行。但是,类似的列表实用程序函数在 [stdlib] 中的 std.list 中可用于 Lua 5。

Lua 使用表格作为列表的巧妙语法糖正等待着被利用... 许多这些函数毫不掩饰地具有函数式风格,非常有用,尽管如果你不是函数式程序员,你可能需要一段时间才能习惯它们。

-- 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

最近更改 · 偏好设置
编辑 · 历史
最后编辑于 2007 年 1 月 2 日凌晨 2:37 GMT (差异)