From f28763f3afcd2c51e9b69318e3749b6bb0a4f1ea Mon Sep 17 00:00:00 2001 From: Case Duckworth Date: Mon, 1 Apr 2024 22:16:50 -0500 Subject: Implement list length This lays groundwork for arity checks. --- type.lua | 14 ++++++++++++++ util.lua | 14 ++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/type.lua b/type.lua index 3c26188..07f78f1 100644 --- a/type.lua +++ b/type.lua @@ -97,6 +97,20 @@ function m.cons (a, b) end return "(" .. table.concat(out, " ") .. ")" end, + __len = + function (self) + local function go (lis, acc) + -- improper lists don't have lengths + -- ... but don't error here. + if not m.isa(lis, "cons") then + return nil + end + if lis[2] == m.null then return acc + else return go(lis[2], acc+1) + end + end + return go(self, 1) + end, } return setmetatable(t, mt) end diff --git a/util.lua b/util.lua index 938848c..b5a57b1 100644 --- a/util.lua +++ b/util.lua @@ -1,11 +1,17 @@ --- lam.util -local util = {} -local unpack = table.unpack or unpack +local m = {} -function util.pop (tbl) +function m.pop (tbl) + --[[ Remove the first element from TBL. ]] return table.remove(tbl, 1) end +function m.arity (r, min, max) + --[[ Return whether R is within MIN and MAX (inclusive). ]] + local len = #r + return len >= min and len <= max +end + --- -return util +return m -- cgit 1.4.1-21-gabe81