-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatch.lua
More file actions
56 lines (50 loc) · 1.08 KB
/
match.lua
File metadata and controls
56 lines (50 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-- match.lua --
--
-- a match expression
--
-- usage:
-- local m = soup.match()
-- :case(6,
-- "six" >> cout)
-- :case(7,
-- "seveen" >> cout)
-- :case(function(x) return x % 2 == 0 end,
-- "even" >> cout)
-- :case(function(x) return x % 2 ~= 0 end,
-- "odd" >> cout)
-- :otherwise(
-- "idk" >> cout << cout.endl)
-- m(6)()
--
-- part of the soup files
-- https://github.com/if-not-nil/soup
return function()
local t = { cases = {}, predicates = {}, default = nil }
-- TODO: deep equality checks between tables
function t:case(key, result)
if (type(key) == "function")
or (type(key) == table and key["__call"]) then
self.predicates[key] = result
return self
end
self.cases[key] = result
return self
end
function t:otherwise(result)
self.default = result
return self
end
function t:match(value)
if self.cases[value] then return self.cases[value] end
for k, v in pairs(self.predicates) do
if k(value) then return v end
end
return self.default
end
setmetatable(t, {
__call = function(self, with)
return self:match(with)
end,
})
return t
end