# Function declaration inside loop

**URL:** <https://discourse.julialang.org/t/function-declaration-inside-loop/23535>\
**Category:** General Usage\
**Created:** [April 25, 2019, 10:51pm UTC](https://discourse.julialang.org/t/function-declaration-inside-loop/23535 "2019-04-25T22:51:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![askvorts](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/askvorts/32/7120_2.png) [@askvorts](https://discourse.julialang.org/u/askvorts)\
**Post date:** [April 25, 2019, 10:51pm UTC](https://discourse.julialang.org/t/function-declaration-inside-loop/23535/1 "2019-04-25T22:51:42Z")

</div>

Having a function declaration inside a loop seems to me somewhat awkward, …but it works. Which would be a better/recommended way оf doing this?

```julia
using Optim
euribor = [0.201 0.335 0.406 0.516 0.652 0.805 0.964 1.119 1.264 1.392 1.604 1.824 2.01 2.079 2.098; 0.202 0.336 0.405 0.51 0.64 0.785 0.936 1.086 1.225 1.35 1.562 1.783 1.971 2.041 2.061]
function nss(p) 
    t = [1.0 , 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30.0]; 
    p[1] .+ 
    p[2] * (1 .- exp.(-t/p[5])) ./ (t/p[5]) .+ 
    p[3] * ((1 .- exp.(-t/p[5])) ./ (t/p[5]) .- exp.(-t/p[5])) .+
    p[4] * ((1 .- exp.(-t/p[6])) ./ (t/p[6]) .- exp.(-t/p[6]))   
end
function lsquares(p,observed) 
    sum((nss(p) .- observed) .^2) 
end
for i = 1:2
    ice(p) = lsquares(p, euribor[i,:])
    p0 = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0]
    resp = optimize(ice, p0, BFGS()) 
    println(Optim.minimizer(resp),Optim.minimum(resp))
end

```

---

<div class="post-metadata">

**Author:** ![dpsanders](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dpsanders/32/3573_2.png) [@dpsanders](https://discourse.julialang.org/u/dpsanders)\
**Post date:** [April 25, 2019, 11:11pm UTC](https://discourse.julialang.org/t/function-declaration-inside-loop/23535/2 "2019-04-25T23:11:27Z")

</div>

Use an anonymous function.

---

<div class="post-metadata">

**Author:** ![askvorts](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/askvorts/32/7120_2.png) [@askvorts](https://discourse.julialang.org/u/askvorts)\
**Post date:** [April 26, 2019, 8:19am UTC](https://discourse.julialang.org/t/function-declaration-inside-loop/23535/3 "2019-04-26T08:19:21Z")

</div>

Indeed! Thank you
