Skip to content

Commit

Permalink
Merge pull request #1525 from BioTurboNick/enumerate-cond-gen
Browse files Browse the repository at this point in the history
Support `enumerate` in conditional generators/comprehensions
  • Loading branch information
ToucheSir authored Sep 22, 2024
2 parents 0759953 + 7404cd8 commit f17ba75
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@ end
@adjoint function enumerate(xs)
back(::AbstractArray{Nothing}) = nothing
back(dy::NamedTuple{(:itr,)}) = tuple(dy.itr)
back(diys::AbstractArray{Union{Nothing, T}}) where T = (map(x -> x === nothing ? x : last(x), diys),)
back(diys) = (map(last, diys),)
enumerate(xs), back
end
Expand Down
13 changes: 13 additions & 0 deletions test/lib/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,19 @@ end
sum(v for (_, v) in d)
end
@test gradient(f_comprehension, w)[1] == ones(5)

w = [randn(5); NaN]
function f_generator_conditional(w)
d = Dict{Int, Float64}(i => v for (i,v) in enumerate(w) if !isnan(v))
sum(v for (_, v) in d)
end
@test gradient(f_generator_conditional, w)[1] == [ones(5); nothing]

function f_comprehension_conditional(w)
d = Dict{Int, Float64}(i => v for (i,v) in enumerate(w) if !isnan(v))
sum(v for (_, v) in d)
end
@test gradient(f_comprehension_conditional, w)[1] == [ones(5); nothing]
end

@testset "_reverse" begin
Expand Down

0 comments on commit f17ba75

Please sign in to comment.