# Scope and anonymous functions

**URL:** https://discourse.julialang.org/t/scope-and-anonymous-functions/48590
**Category:** General Usage
**Created:** [October 18, 2020, 4:05pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590 "2020-10-18T16:05:02Z")
**Posts on this page:** 8
**Page:** 1

<div class="post-metadata">

### Author: ![Wikunia](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wikunia/32/2180_2.png) [@Wikunia](https://discourse.julialang.org/u/Wikunia)
#### Post date: [October 18, 2020, 4:05pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/1 "2020-10-18T16:05:02Z")

</div>

I need help 😃

What is the difference between:

```julia
function a() 
        funcs = []
        i = 1
        for j=1:100
           push!(funcs, (args...)->i)
           i += 1
       end
       return funcs
end
b = a()
b[1]()

```

and

```julia
function c() 
        funcs = []
        for i=1:100
           push!(funcs, (args...)->i)
       end
       return funcs
end
d = c()
d[1]()

```

The first one returns 101 for every call of `b[x]()` and the second one does the expected thing of `d[x]() = x`

I put it into a function to avoid global scope issues.

What I also find interesting is that the repl shows something like:

```julia
100-element Array{Any,1}:
 #76 (generic function with 1 method)
 #76 (generic function with 1 method)
 #76 (generic function with 1 method)

```

for both of them which looks like it creates the same function over and over again? (Based on the name `#76`).

@TheCedarPrince is also interested 😄

---

<div class="post-metadata">

### Author: ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)
#### Post date: [October 18, 2020, 4:19pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/2 "2020-10-18T16:19:05Z")

</div>

[https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope](https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope)

the behavior should be explained here, My guess is your first function should fall into:

> When `x = <value>`
> 
> 1. Existing Local

because function is a hard local scope and your assignment is in a soft local scope (`for`).

* * *

One way to make your first function to “behave” is by forcing a local variable:

```julia
function a()
               funcs = []
               i = 1
               for j=1:100
                  local k=i
                  push!(funcs, (args...)->k)
                  i += 1
               end
              return funcs
       end

```

---

<div class="post-metadata">

### Author: ![lhnguyen-vn](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lhnguyen-vn/32/15449_2.png) [@lhnguyen-vn](https://discourse.julialang.org/u/lhnguyen-vn)
#### Post date: [October 18, 2020, 4:28pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/3 "2020-10-18T16:28:11Z")

</div>

The behavior of `a()` is due to the way closure works, as all the functions in `funcs` will return the local variable `i` as it updates. The second scenario is a bit different because the iterator variable `i` is new for each iteration. Besides @jling recommendation, it’s also possible to use the `let` block for the first case.

---

<div class="post-metadata">

### Author: ![Wikunia](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wikunia/32/2180_2.png) [@Wikunia](https://discourse.julialang.org/u/Wikunia)
#### Post date: [October 18, 2020, 4:29pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/4 "2020-10-18T16:29:18Z")

</div>

Thanks for the explanation and the way to avoid this. The other question is why do all those functions have the same name?

---

<div class="post-metadata">

### Author: ![Mikael\_Ohman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikael_ohman/32/13609_2.png) [@Mikael\_Ohman](https://discourse.julialang.org/u/Mikael_Ohman)
#### Post date: [October 18, 2020, 4:37pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/5 "2020-10-18T16:37:37Z")

</div>

> [@Wikunia](#):
>
> The other question is why do all those functions have the same name?

Just the way @show works for arrays?

```julia
julia> @show d[1]
d[1] = var"#1#2"{Int64}(1)
#1 (generic function with 1 method)

julia> @show d[2]
d[2] = var"#1#2"{Int64}(2)
#1 (generic function with 1 method)

```

---

<div class="post-metadata">

### Author: ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)
#### Post date: [October 18, 2020, 4:42pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/6 "2020-10-18T16:42:29Z")

</div>

Because that _is_ their name:

```julia
# a is generated with the second loop
julia> a[1] === a[2]
false

julia> typeof(a[1]) === typeof(a[2])
true

julia> a[1]
#1 (generic function with 1 method)

julia> a[1]()
1

julia> a[2]()
2

```

It’s just that they box different values:

```julia
julia> dump(a[1])
#1 (function of type var"#1#2"{Int64})
  i: Int64 1

julia> dump(a[2])
#1 (function of type var"#1#2"{Int64})
  i: Int64 2

```

Remember, anonymous functions are implemented as callable structs, where each variable that is captured refers to a field. The second loop creates multiple different instances of the same struct, which capture different values in their single field. The first one captures a reference to _the same value/binding_.

> **Lowered code of your anonymous function**
>
> ```julia
> julia> Meta.@lower (args...) -> i
> :($(Expr(:thunk, CodeInfo(
> @ none within `top-level scope'
> 1 ─ $(Expr(:thunk, CodeInfo(
> @ none within `top-level scope'
> 1 ─ global var"#7#8"
> │ const var"#7#8"
> │ %3 = Core._structtype(Main, Symbol("#7#8"), Core.svec(), Core.svec(), false, 0)
> │ var"#7#8" = %3
> │ Core._setsuper!(var"#7#8", Core.Function)
> │ Core._typebody!(var"#7#8", Core.svec())
> └── return
> )))
> │ %2 = var"#7#8"
> │ %3 = Core.apply_type(Vararg, Core.Any)
> │ %4 = Core.svec(%2, %3)
> │ %5 = Core.svec()
> │ %6 = Core.svec(%4, %5, $(QuoteNode(:(#= REPL[45]:1 =#))))
> │ $(Expr(:method, false, :(%6), CodeInfo(quote
> return i
> end)))
> │ #7 = %new(var"#7#8")
> └── return #7
> ))))
> 
> ```

---

<div class="post-metadata">

### Author: ![Wikunia](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wikunia/32/2180_2.png) [@Wikunia](https://discourse.julialang.org/u/Wikunia)
#### Post date: [October 18, 2020, 4:44pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/7 "2020-10-18T16:44:03Z")

</div>

I learn a lot today 🙂 Thanks for the example and explanation,

---

<div class="post-metadata">

### Author: ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)
#### Post date: [October 18, 2020, 8:06pm UTC](https://discourse.julialang.org/t/scope-and-anonymous-functions/48590/8 "2020-10-18T20:06:10Z")

</div>

I talk a little about the scope of variables inside loops [here](https://github.com/vancleve/julia_logo_latex), and I really deepen the topic [here](https://discourse.julialang.org/t/i-thought-i-understood-pass-by-sharing-in-julia-until-i-found-this/46897/24).
