local function indent(text)
return " " .. string.gsub(text, "\n", "\n ")
end
local translators = { }
local function translate(expr)
return translators[expr.expr_type](expr)
end
function translators.var(expr)
return expr.name
end
function translators.abs(expr)
local param = expr.param
local body = translate(expr.body)
return "function(" .. param .. ")\n" .. indent("return " .. body) .. "\nend"
end
function translators.app(expr)
local fn = translate(expr.fn)
local arg = translate(expr.arg)
return "(" .. fn .. ")(" .. arg .. ")"
end
function translators.str(expr)
return string.format("%q", expr.value)
end
local expr = {
expr_type = "abs",
param = "_",
body = {
expr_type = "app",
fn = {
expr_type = "abs",
param = "x",
body = {
expr_type = "app",
fn = {
expr_type = "abs",
param = "y",
body = { expr_type = "var", name = "y" },
},
arg = { expr_type = "var", name = "x" },
},
},
arg = { expr_type = "str", value = "Hello, world!" },
},
}
print(translate(expr))
bG9jYWwgZnVuY3Rpb24gaW5kZW50KHRleHQpCglyZXR1cm4gIiAgICAiIC4uIHN0cmluZy5nc3ViKHRleHQsICJcbiIsICJcbiAgICAiKQplbmQKCmxvY2FsIHRyYW5zbGF0b3JzID0geyB9Cgpsb2NhbCBmdW5jdGlvbiB0cmFuc2xhdGUoZXhwcikKCXJldHVybiB0cmFuc2xhdG9yc1tleHByLmV4cHJfdHlwZV0oZXhwcikKZW5kCgpmdW5jdGlvbiB0cmFuc2xhdG9ycy52YXIoZXhwcikKCXJldHVybiBleHByLm5hbWUKZW5kCgpmdW5jdGlvbiB0cmFuc2xhdG9ycy5hYnMoZXhwcikKCWxvY2FsIHBhcmFtID0gZXhwci5wYXJhbQoJbG9jYWwgYm9keSA9IHRyYW5zbGF0ZShleHByLmJvZHkpCglyZXR1cm4gImZ1bmN0aW9uKCIgLi4gcGFyYW0gLi4gIilcbiIgLi4gaW5kZW50KCJyZXR1cm4gIiAuLiBib2R5KSAuLiAiXG5lbmQiCmVuZAoKZnVuY3Rpb24gdHJhbnNsYXRvcnMuYXBwKGV4cHIpCglsb2NhbCBmbiA9IHRyYW5zbGF0ZShleHByLmZuKQoJbG9jYWwg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