Basically Julia is a lisp, if you look at metaprogramming for a description. Basically, code afaics consists of Expr objects. It takes a little getting used to, but it can basically do arbitrary stuff.(And arbitrarilly bad too as we know, but competence is up to the developer.) For illustration, below a macro:
Code: Select all
function destructuring_bind_fun(args, array, body, n)
if length(args) == 0 #No variables to fill, done.
return body
else if isa(args[1], Symbol)
return quote
$(args[1]) = ($array)[$n]
$(destructuring_bind_fun(args[2:],array, body, n+1))
end
else
a = gensym()
return quote
$a = ($array)[$n]
$(destructuring_bind_fun(args[1].args,a,
quote $(destructuring_bind_fun(args[2:],array, body, n+1)) end,1))
end
end
end
# Due to use of Expr and different styles, `destructuring_bind` wont be as use
# full in Julia as in the lisps. (Maybe a `destructure_expr` might be.)
macro destructuring_bind(args, array, body)
assert(args.head == :cell1d, # Poor error message.
"I am a restrictive bitch now so i can be nicer later, promise.")
return destructuring_bind_fun(args.args, array, body, 1)
end
# Users need to put `@` in front, i think users need to be more first-class.
@destructuring_bind{a,b,{c,d},q} {1,2,{3,4},5} {a,b,c,d,q} #-> 1,2,3,4,5