Metaprogramming with anonymous functions

192 views
Skip to first unread message

David Gold

unread,
Aug 1, 2015, 12:31:19 PM8/1/15
to julia-dev
To the extent that the following is not possible, then I would like to know if it is an appropriate feature request.

In short, I'd like to extract the expression from which an anonymous function is defined and manipulate it in order to form a new, derived anonymous function. In particular, in

julia> f = x -> x + a
(anonymous function)

julia
> f.code
AST
(:($(Expr(:lambda, Any[:(x::Any)], Any[Any[Any[:x,:Any,0]],Any[],0,Any[]], :(begin # none, line 1:
   
return x + Main.a
end)))))

I would love to be able to extract the expression

:(begin # none, line 1:
   
return x + Main.a
end)

change `Main` to the name of another module, and generate a new anonymous function. 

It would be even cooler if the new anonymous function lived in the scope in which the "regeneration" is called (as opposed to necessarily global scope), so that if one had

module Foo

let a
= 10
   
global with
   
function with(f, b)
        _f
= regenerate(f)
        _f
(b)
   
end
end

end

then

Foo.with(5) do x
    x
+ a
end

would return 15.

My use case for this is in developing an API that can mimic delayed evaluation without relying on (user-facing) macros by using the `do` block syntax as a vessel for an unevaluated expression passed by way of an anonymous function's code. But that only works if I can get at the code in a form that I can manipulate in Julia.

Thoughts?

Tim Holy

unread,
Aug 1, 2015, 1:05:04 PM8/1/15
to juli...@googlegroups.com
You can do this now. Nice tools:

@edit show(STDOUT, f.code)
# Aha! uncompressed_ast looks like a useful function
ast = Base.uncompressed_ast(f.code)
dump(ast)

and from there you should be able to figure it out.

--Tim

Tom Breloff

unread,
Aug 1, 2015, 1:08:11 PM8/1/15
to juli...@googlegroups.com
Have you tried FastAnonymous.jl? You can swap out the internals before compilation pretty easily... I do this for a pub/sub event routing framework that I built, and performance is pretty good. Someday I might get around to releasing it as a standalone package (but I seem to be adding to my project list faster than I can deliver)

David Gold

unread,
Aug 1, 2015, 7:27:19 PM8/1/15
to julia-dev
@Tim -- ahah! Thank you very much for the tip, as well as for the general strategy for finding such useful functions. I'm excited to see what use I can make of this.

@Tom -- no, I haven't. But I'll have to take a look now. Thank you for the recommendation!
Reply all
Reply to author
Forward
0 new messages