fork download
  1. local function indent(text)
  2. return " " .. string.gsub(text, "\n", "\n ")
  3. end
  4.  
  5. local translators = { }
  6.  
  7. local function translate(expr)
  8. return translators[expr.expr_type](expr)
  9. end
  10.  
  11. function translators.var(expr)
  12. return expr.name
  13. end
  14.  
  15. function translators.abs(expr)
  16. local param = expr.param
  17. local body = translate(expr.body)
  18. return "function(" .. param .. ")\n" .. indent("return " .. body) .. "\nend"
  19. end
  20.  
  21. function translators.app(expr)
  22. local fn = translate(expr.fn)
  23. local arg = translate(expr.arg)
  24. return "(" .. fn .. ")(" .. arg .. ")"
  25. end
  26.  
  27. function translators.str(expr)
  28. return string.format("%q", expr.value)
  29. end
  30.  
  31. local expr = {
  32. expr_type = "abs",
  33. param = "_",
  34. body = {
  35. expr_type = "app",
  36. fn = {
  37. expr_type = "abs",
  38. param = "x",
  39. body = {
  40. expr_type = "app",
  41. fn = {
  42. expr_type = "abs",
  43. param = "y",
  44. body = { expr_type = "var", name = "y" },
  45. },
  46. arg = { expr_type = "var", name = "x" },
  47. },
  48. },
  49. arg = { expr_type = "str", value = "Hello, world!" },
  50. },
  51. }
  52.  
  53. print(translate(expr))
  54.  
Success #stdin #stdout 0s 2788KB
stdin
Standard input is empty
stdout
function(_)
    return (function(x)
        return (function(y)
            return y
        end)(x)
    end)("Hello, world!")
end