# Is this a bug? Nested Functions and NLsolve

**URL:** <https://discourse.julialang.org/t/is-this-a-bug-nested-functions-and-nlsolve/86085>\
**Category:** General Usage\
**Tags:** bug, optimization, functions\
**Created:** [August 21, 2022, 12:15pm UTC](https://discourse.julialang.org/t/is-this-a-bug-nested-functions-and-nlsolve/86085 "2022-08-21T12:15:41Z")\
**Posts on this page:** 1\
**Page:** 2

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [August 22, 2022, 10:53am UTC](https://discourse.julialang.org/t/is-this-a-bug-nested-functions-and-nlsolve/86085/23 "2022-08-22T10:53:55Z")

</div>

Yes, after I saw the nsolve example again I deleted the post. It is more tricky than that.

ps: I was now a bit surprised I didn´t fall into this trap more frequently. I guess I do not change parameters that often. So, playing around, maybe this is one alternative way to write it safely:

```julia
julia> function test4()
           fun(x,p) = (x-p)^2
           p = 0.0
           res = Float64[]
           for x in 1.0:0.1:2.0
               p = x
               let p = p
                   f(x) = fun(x,p)
                   push!(res, optimize(f, -2p, 2p).minimizer)
               end
           end
           return res
       end
test4 (generic function with 1 method)

```

And I think nobody mentioned the `FastClosures` package as well, which can make the syntax somewhat prettier:

```julia
julia> using FastClosures
       function test5()
           fun(x,p) = (x-p)^2
           p = 0.0
           res = Float64[]
           for x in 1.0:0.1:2.0
               p = x
               f = @closure (x) -> fun(x,p)
               push!(res, optimize(f, -2p, 2p).minimizer)
           end
           return res
       end
test5 (generic function with 1 method)

```

[Previous page](https://discourse.julialang.org/t/is-this-a-bug-nested-functions-and-nlsolve/86085.md?page=1)
