# Evaluation in calling scope?

**URL:** https://discourse.julialang.org/t/evaluation-in-calling-scope/34897
**Category:** General Usage
**Created:** [February 20, 2020, 11:15am UTC](https://discourse.julialang.org/t/evaluation-in-calling-scope/34897 "2020-02-20T11:15:55Z")
**Posts on this page:** 1
**Showing post:** 13

<div class="post-metadata">

### Author: ![tomtom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tomtom/32/5106_2.png) [@tomtom](https://discourse.julialang.org/u/tomtom)
#### Post date: [February 21, 2020, 2:02pm UTC](https://discourse.julialang.org/t/evaluation-in-calling-scope/34897/13 "2020-02-21T14:02:27Z")

</div>

> [@tomtom](#):
>
> why the warntype in `f2`

it’s because `const` is missing, see [here](https://discourse.julialang.org/t/warntype-from-anonymous-function/34975)

so, here’s the solution for **calling scope evaluation** , despite the fact that only relatively simple expression could be handled:

```julia
function expr2fun(ex)
    vars = getvars(ex)
    return eval(:($Expr(:meta, :inline); $vars -> $ex) ) # is it the correct way to inline???
end

getvars(ex) = Expr(:tuple, _getvars(ex)...)
_getvars(ex::Symbol) = [ex]
function _getvars(ex::Expr)
    vars = Symbol[]
    if ex.head == :call
        for arg in ex.args[2:end]
            append!(vars, _getvars(arg) )
        end
    end
    return unique(vars)
end
_getvars(ex) = Symbol[] # fallback

ex = :(x * (y - x) - (x * y - 2) )
const fun = expr2fun(ex) # const is needed to avoid warntype !

@inline f1(x, y) = x * (y - x) - (x * y - 2)
@inline f2(x ,y) = fun(x, y) # calling slope evaluation

julia> f1(1, 2) == f2(1, 2)
true
julia> @btime f1(1, 2);
  0.022 ns (0 allocations: 0 bytes)
julia> @btime f2(1, 2);
  0.022 ns (0 allocations: 0 bytes)
julia> @btime fun(1, 2);
  0.022 ns (0 allocations: 0 bytes)

```

hope it helps.

---

_[View the full topic](https://discourse.julialang.org/t/evaluation-in-calling-scope/34897)._
