`eval` operates in global scope, which explains the behavior you are seeing.
Julia has closures [1] and anonymous functions [2] built-in, so you can do things like below instead (note that there is currently non-trivial overhead for anonymous functions, so don't use them in a tight loop. they are usually sufficiently performant for interactive graphics/gui type things though) funky(ff::Function) = (x,y) -> ff(x,y) funky(+)(1,2) == 3 funfun(x,y) = funky(+)(x,y) funfun(4,5) etc... [1] http://en.wikipedia.org/wiki/Closure_%28computer_programming%29 [2] http://en.wikipedia.org/wiki/Anonymous_function On Wed, May 6, 2015 at 8:58 PM, Evan Pu <[email protected]> wrote: > Hi, just a quick question on the scope/environment of an expression. > > I am using the Expr construct inside a function to create an expression, > and I would then want to use this expression in various different places. > Here's a short example > > First we have a simple function "funky" that takes in a function "ff", and > applies it to two symbolic arguments :x and :y > julia> function funky(ff::Function) > Expr(:call, ff, :x, :y) > end > funky (generic function with 1 method) > > > We define x and y to be 1 and 2 respectively > julia> x,y = 1,2 > (1,2) > > > No surprise here, when funky is passed with the function "+", it adds x > and y together > julia> eval(funky(+)) > 3 > > > However, now I want to use this expression with different bindings for x > and y, I attempt the following > julia> function funfun(x, y) > eval(funky(+)) > end > funfun (generic function with 1 method) > > > Which doesn't seem to work. Here the result is sitll 3, presumably it is > using the earlier bindings of x=1, y=2 > julia> funfun(4,5) > 3 > > I would really liked the last result to be 9. > > > So far it seems the expression uses static scoping and it's looking up the > binding for :x and :y in the frame generated by calling "funky", and not > finding it there, it looks up :x and :y in the > global frame, which is 1 and 2. > Is there a way to bind the symbols in an expression to different things? > is there like an "environment" dictionary where we can mess with, or is > there some clean way of doing it? > > Much much much appreciated!!! > --evan >
