Skip to content

Variable scope in anonymous functions #148

@vivekbhattacharya

Description

@vivekbhattacharya

I am confused about how Polyester handles arguments to anonymous functions. In short, why does the last example below not work?

function temp(x, y)
     return x + y
end

outputs = zeros(Float64, 100)

# This works
Polyester.@batch for i = 1:100
     myfunc = x -> temp(x, i)
     outputs[i] = myfunc(1)
end

# This also works
vals = collect(1:100)
Polyester.@batch for i = 1:100
     outputs[i] = 1 + vals[i]
end

# This does not
vals = collect(1:100)
Polyester.@batch for i = 1:100
     myfunc = x -> temp(x, vals[i])
     outputs[i] = myfunc(1)
end

Running it gives me the following error:

ERROR: UndefVarError: ##vals#373869 not defined
Stacktrace:
 [1] (::var"#183#186"{Int64})(x#373868::Int64)
   @ Main ./REPL[102]:2
 [2] macro expansion
   @ ./REPL[102]:3 [inlined]
 [3] #182
   @ ~/.julia/packages/Polyester/4yL9u/src/closure.jl:309 [inlined]
 [4] batch(::var"#182#185", ::Val{false}, ::Tuple{}, ::Tuple{}, ::Tuple{Static.StaticInt{100}, Int64}, ::Static.StaticInt{1}, ::Static.StaticInt{1}, ::Polyester.NoLoop, ::Polyester.CombineIndices, ::Vector{Int64}, ::Vector{Float64})
   @ Polyester ~/.julia/packages/Polyester/4yL9u/src/batch.jl:323
 [5] top-level scope
   @ ~/.julia/packages/Polyester/4yL9u/src/closure.jl:456

A related question is that if I instead define the function as the following, I get another error (that it does not recognize myfunc).

# This does not work
Polyester.@batch for i = 1:100
     myfunc(x) = temp(x, i) # here is the difference.
     outputs[i] = myfunc(1)
end

Thanks for the help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions