# Storing evaled function inside a struct

**URL:** <https://discourse.julialang.org/t/storing-evaled-function-inside-a-struct/35454>\
**Category:** General Usage\
**Tags:** question\
**Created:** [March 3, 2020, 10:48am UTC](https://discourse.julialang.org/t/storing-evaled-function-inside-a-struct/35454 "2020-03-03T10:48:52Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![Karajan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/karajan/32/8545_2.png) [@Karajan](https://discourse.julialang.org/u/Karajan)\
**Post date:** [March 3, 2020, 12:57pm UTC](https://discourse.julialang.org/t/storing-evaled-function-inside-a-struct/35454/7 "2020-03-03T12:57:34Z")

</div>

You are right, I had hoped it would be easier without this but I guess I’ll start from the beginning:

I have a bunch of functions and a cost function

```julia
f1(a, b) = ...
f2(a, d) = ...
f3(b, c) = ...
cost(a, b, c, d) = f1(a, b) + f2(a, d) + f3(b, c)

```

with some other equations to calculate the values `a, b, c, d`:

```julia
a = 2d
c = a * b
...

```

Now the user has the choice of setting some of those values as fixed, some to be in some range, some as free (do with these whatever). Then I want to find the best values for those parameters I can change via optimization.  
If I set `a` as fixed and `b` to be in some range (to be optimized), I can get both `c` and `d` from the equations above, so my function would look like

```julia
function (x)
    a = 2 # the const value I want
    d = 1 # == a / 2; I get this value by evaluating this equation while generating the expressions
    b = x[1]
    c = a * b
    cost(a, b, c, d)
end

```

If I only set `b` to be fixed, `d` can be optimized and the function will look like

```julia
function (x)
    b = 5 # the const value I want
    d = x[1]
    a = 2d
    c = a * b
    cost(a, b, c, d)
end

```

The resolving of these dependencies takes some time, which is why I wish to do this once instead on doing this in the cost function.

I don’t know how to do this just with functions without a big performance penalty to the cost function, that’s why I create the function from expressions and need the `eval`.

---

_[View the full topic](https://discourse.julialang.org/t/storing-evaled-function-inside-a-struct/35454)._
