git @ Cat's Eye Technologies Decoy / master src / decoy / model / list.lua
master

Tree @master (Download .tar.gz)

list.lua @masterraw · history · blame

--
-- decoy_cons.lua
--

-- SPDX-FileCopyrightText: Copyright (c) 2023-2024 Chris Pressey, Cat's Eye Technologies.
-- This work is distributed under a 2-clause BSD license. For more information, see:
-- SPDX-License-Identifier: LicenseRef-BSD-2-Clause-X-Decoy

local Cons = {}

local Nil = {}

function Cons:head()
    return self._head
end

function Cons:tail()
    return self._tail
end

Cons.new = function(head, tail)
    assert(head ~= nil)
    assert(tail ~= nil)
    local self = {
        _head = head,
        _tail = tail,
    }
    setmetatable(self, {__index = Cons})
    return self
end

Cons.is_class_of = function(obj)
    local mt = getmetatable(obj)
    return mt and mt.__index == Cons
end

Cons.table_to_list = function(es)
    local e = Nil
    local i
    for i = #es, 1, -1 do
        do_debug("util", function()
            print("--> consing", i, depict(es[i]))
        end)
        e = Cons.new(es[i], e)
    end
    do_debug("util", function()
        print("--> consed", depict(e), render(e))
    end)
    return e
end

Cons.list_to_table = function(e)
    local t = {}
    while e ~= nil do
        table.insert(t, e._head)
        e = e._tail
    end
    return t
end

return {
    Cons = Cons,
    Nil = Nil,
}