# What is the right way to construct and then run a Julia function programmatically?

**URL:** https://discourse.julialang.org/t/what-is-the-right-way-to-construct-and-then-run-a-julia-function-programmatically/25845
**Category:** General Usage
**Tags:** macros
**Created:** [June 29, 2019, 6:51pm UTC](https://discourse.julialang.org/t/what-is-the-right-way-to-construct-and-then-run-a-julia-function-programmatically/25845 "2019-06-29T18:51:30Z")
**Posts on this page:** 1
**Showing post:** 13

<div class="post-metadata">

### Author: ![oxinabox](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oxinabox/32/206603_2.png) [@oxinabox](https://discourse.julialang.org/u/oxinabox)
#### Post date: [June 30, 2019, 6:45pm UTC](https://discourse.julialang.org/t/what-is-the-right-way-to-construct-and-then-run-a-julia-function-programmatically/25845/13 "2019-06-30T18:45:37Z")

</div>

> [@Nathaniel](#):
>
> How good is the compiler at optimising chains of anonymous functions, as opposed to functions generated from expressions in the ‘normal’ way? For example, can I trust it to turn `x->(x->x+2)((x->x+2)(x))` into `x->x+4` ? If so, I might not need to generate expressions at all.

Anonymous functions optimize just fine

```julia
julia> function makefun()
    f1 = x->x+2
    f2 = x->(f1(f1(x)))
    return f2
end

makefun (generic function with 1 methods)

julia> aa = makefun();
julia> @code_typed aa(3)

CodeInfo(
│╻╷ #74 1 ─ %1 = (Base.add_int)(x, 2)::Int64
││╻ + │ %2 = (Base.add_int)(%1, 2)::Int64
│ └── return %2
) => Int64

julia> bb(x) = x+2+2;
julia> @code_typed bb(3)

CodeInfo(
│╻╷ +1 1 ─ %1 = (Base.add_int)(x, 2)::Int64
││┃ + │ %2 = (Base.add_int)(%1, 2)::Int64
│ └── return %2
) => Int64

```

Noted that `aa` and `bb` get lowered to exactly the same thing.

* * *

> Is it feasible to use Flux.jl (or some other existing automatic differentiation package) on huge chains of anonymous functions like this?

Yes.  
(well flux isn’t AD, but Flux will invoke Tracker.jl (or oneday Zygote.jl) and both have no issue with this.)

---

_[View the full topic](https://discourse.julialang.org/t/what-is-the-right-way-to-construct-and-then-run-a-julia-function-programmatically/25845)._
