31 lines
748 B
Text
31 lines
748 B
Text
local fmt = require "fmt"
|
|
|
|
local NONE <const> = {}
|
|
|
|
class maybe
|
|
static function unit(i) return new maybe(i) end
|
|
|
|
function __construct(public value) end
|
|
|
|
function is_none() return self.value == NONE end
|
|
|
|
function bind(f) return f(self.value) end
|
|
end
|
|
|
|
local function decrement(i)
|
|
if i == NONE then return maybe.unit(NONE) end
|
|
return maybe.unit(i - 1)
|
|
end
|
|
|
|
local function triple(i)
|
|
if i == NONE then return maybe.unit(NONE) end
|
|
return maybe.unit(3 * i)
|
|
end
|
|
|
|
for {3, 4, NONE, 5} as i do
|
|
local m1 = maybe.unit(i)
|
|
local m2 = m1:bind(decrement):bind(triple)
|
|
local s1 = !m1:is_none() ? tostring(m1.value) : "none"
|
|
local s2 = !m2:is_none() ? tostring(m2.value) : "none"
|
|
fmt.print("%4s -> %s", s1, s2)
|
|
end
|