My language in just 10 lines (Just have fun! Jupyter notebook)
t2j(s) = s
function t2j(s::Tuple)
a = (:block, :if, :tuple, :parameters, :kw, :quote, :(=), :(.=), :.)
s[1] in a && return Expr(s[1], t2j.(s[2:end])...)
s[1] === :lambda && return Expr(:(->), Expr(:tuple, s[2]...), t2j(s[3]))
s[1] === :for && return Expr(s[1], Expr(:(=), t2j(s[2]), t2j(s[3])), t2j(s[4]))
s[1] === :using && return Expr(s[1], Expr.(:., s[2:end])...)
Expr(:call, t2j.(s)...)
end
macro tupp(x) t2j(Core.eval(__module__, x)) end
I left all the trouble to Julia! (The name tupp
might stand for “TUPle Processor”.)
Example 1: for loop and if statement
@tupp (:for, :k, (:(:), 1, 5),
(:if, (:iseven, :k),
(:println, "even: ", :k),
(:println, "odd: ", :k)))
Output:
odd: 1
even: 2
odd: 3
even: 4
odd: 5
Example2: Fibonacci numbers with U-combinator
@tupp (:block,
(:(=), :U, (:lambda, (:u,), (:u, :u))),
(:(=), :F, (:lambda, (:u,), (:lambda, (:n, :a, :b),
(:if, (:(==), :n, 0), :a,
((:u, :u), (:-, :n, 1), :b, (:+, :a, :b)))))),
(:(=), :Fib, (:U, :F)),
(:for, :k, (:(:), 1, 10),
(:println, "Fib(", :k, ") = ", (:Fib, :k, 0, 1))))
Output:
Fib(1) = 1
Fib(2) = 1
Fib(3) = 2
Fib(4) = 3
Fib(5) = 5
Fib(6) = 8
Fib(7) = 13
Fib(8) = 21
Fib(9) = 34
Fib(10) = 55
t2j
(tupp to Julia) exmaple:
(:block,
(:(=), :U, (:lambda, (:u,), (:u, :u))),
(:(=), :F, (:lambda, (:u,), (:lambda, (:n, :a, :b),
(:if, (:(==), :n, 0), :a,
((:u, :u), (:-, :n, 1), :b, (:+, :a, :b)))))),
(:(=), :Fib, (:U, :F)),
(:for, :k, (:(:), 1, 10),
(:println, "Fib(", :k, ") = ", (:Fib, :k, 0, 1)))) |> t2j
Output:
quote
U = ((u,)->u(u))
F = ((u,)->((n, a, b)->if n == 0
a
else
(u(u))(n - 1, b, a + b)
end))
Fib = U(F)
for k = 1:10
println("Fib(", k, ") = ", Fib(k, 0, 1))
end
end
Example 3: Polynomial regression of y = \sin(\pi x)
@tupp (:block,
(:using, :Plots),
(:(=), :n, 20),
(:(=), :x, (:range, 0, 2, (:kw, :length, :n))),
(:(=), :y, (:+, (:., :sinpi, (:tuple, :x)), (:*, 0.2, (:randn, :n)))),
(:(=), :xs, (:range, 0, 2, (:kw, :length, 200))),
(:(=), :X, (:.^, :x, (:transpose, (:(:), 0, 3)))),
(:(=), :b, (:\, :X, :y)),
(:scatter, :x, :y, (:kw, :label, "sample")),
(:plot!, :xs, (:., :sinpi, (:tuple, :xs)),
(:kw, :label, "sinpi(x)"),
(:kw, :color, (:quote, :black)),
(:kw, :ls, (:quote, :dash))),
(:plot!, :xs, (:., :evalpoly, (:tuple, :xs, (:Ref, :b))),
(:kw, :label, "degree-3 polynomial"),
(:kw, :color, 2), (:kw, :lw, 2)))