Skip to content

Commit

Permalink
update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
onetonfoot committed May 13, 2020
1 parent 6841736 commit be35bf2
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 3 deletions.
3 changes: 3 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# TODO

* Define nice show methods
2 changes: 1 addition & 1 deletion example/pipe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function pipe(expr)
end

macro pipe(expr)
esc(pipe(expr))
pipe(expr)
end

@testset "Pipe" begin
Expand Down
4 changes: 2 additions & 2 deletions example/slurp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ using ExprManipulation
match_slurp = MExpr(:..., Capture(:var))
match_assign = MExpr(:(=), MExpr(:tuple, Slurp(:lexprs)), Capture(:rexpr))

function create_expr(lexprs, rexpr)
function slurp(lexprs, rexpr)
i = 1
n = length(lexprs)
x = gensym()
Expand Down Expand Up @@ -39,7 +39,7 @@ macro slurp(expr)
if isnothing(matches)
error("Unsupported expression $expr")
end
esc(create_expr(matches[:lexprs], matches[:rexpr]))
esc(slurp(matches[:lexprs], matches[:rexpr]))
end

@slurp a, b..., c = [1,2,3,4,5]
Expand Down
45 changes: 45 additions & 0 deletions example/unpack.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using ExprManipulation
using Base.Meta: show_sexpr

match_assign = MExpr(:(=), Capture(:lexpr), Capture(:rexpr))
match_tuple = MExpr(:tuple, Slurp(x -> x isa Array{Symbol} ,:keys))

function create_expr(lexpr, rexpr)
@assert match_tuple == lexpr "Unsupported left hand expresion $lexpr"
tmp = gensym()
expr = Expr(:block, :($tmp = $rexpr))
args = [:($key = unpack($tmp, Val{$(Expr(:quote, key))}())) for key in lexpr.args ]
append!(expr.args, args)
expr
end

create_expr(lexpr::Symbol, rexpr) = :($lexpr = unpack($rexpr, Val{$(Expr(:quote, lexpr))}()))

unpack(x, ::Val{k}) where {k} = getproperty(x, k)
unpack(x::AbstractDict{Symbol}, ::Val{k}) where {k} = x[k]
unpack(x::AbstractDict{<:AbstractString}, ::Val{k}) where {k} = x[string(k)]

function unpack(expr)
matches = match(match_assign, expr)
!isnothing(matches) ? create_expr(matches.lexpr, matches.rexpr) : error("Unsuppored expression $expr")
end

macro unpack(input_expr)
esc(unpack(input_expr))
end

struct Data
a
b
c
d
e
f
end

data = Data(1, 2, 3 ,4, 5, 6)
dict = Dict(:y=>2, "z"=>3)

@unpack a, b, f = data
@unpack d = data
@unpack y, z = dict

0 comments on commit be35bf2

Please sign in to comment.