duckie :)

This commit is contained in:
2025-02-15 14:58:27 +03:00
parent 40c9af4803
commit d4c79731b0
6 changed files with 239 additions and 4 deletions

View File

@ -0,0 +1,98 @@
---@class List
local List = {}
local function reduce(list, f, init)
local acc = init
for i, v in ipairs(list) do
acc = f(v, acc, i)
end
return acc
end
local function filter(list, predicate)
return reduce(list, function(el, acc, i)
if predicate(el) then
table.insert(acc, el)
end
return acc
end, List.create{})
end
local function shallow_copy(t)
local t2 = {}
for k, v in ipairs(t) do
t2[k] = v
end
return t2
end
List.__index = List
setmetatable(List, {
__call = function(self, ...)
local args = {...}
if #args == 0 then
return List.create()
end
if type(args[1]) == "table" then
return List.create(args[1])
end
return List.create(args)
end
})
---Constructs a new list from the given table.
---@param from table?
---@return List
function List.create(from)
from = from or {}
local l = shallow_copy(from)
return setmetatable(l, List)
end
function List:__tostring()
local s = "List(" .. table.concat(self, ", ", 1, #self) .. ")"
return s
end
---Appends v to the end of the list.
---@param v any
function List:push(v)
table.insert(self, v)
end
---Removes the last element in the list and returns it.
---@return any
function List:pop()
return table.remove(self, #self)
end
---Reduce.
---@param f function called with element, accumulator, index
---@param init any initial value of accumulator
---@return any
function List:reduce(f, init)
return reduce(self, f, init)
end
---Returns a new List of all elements of this list that match the predicate function.
---@param predicate function called with element
---@return List
function List:filter(predicate)
return filter(self, predicate)
end
---Returns the index of value, if it exists in the list, -1 otherwise.
---@param value any
---@return integer
function List:find(value)
local idx = -1
for i, v in ipairs(self) do
if v == value then
idx = i
break
end
end
return idx
end
return List