Skip to content

Commit

Permalink
Support enumerate in conditional generators/comprehensions
Browse files Browse the repository at this point in the history
  • Loading branch information
BioTurboNick committed Sep 17, 2024
1 parent 0759953 commit 7404cd8
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 7404cd8

Please sign in to comment.