Skip to content

Commit f2e168a

Browse files
authored
Add filter(f, ::Namedtuple) (#50795)
1 parent d54a455 commit f2e168a

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ New library features
102102
data-races. Or use the callback form of `open` to have all that handled
103103
automatically.
104104
* `@timed` now additionally returns the elapsed compilation and recompilation time ([#52889])
105+
* `filter` can now act on a `NamedTuple` ([#50795]).
105106

106107
Standard library changes
107108
------------------------

base/namedtuple.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,8 @@ function map(f, nt::NamedTuple{names}, nts::NamedTuple...) where names
268268
NamedTuple{names}(map(f, map(Tuple, (nt, nts...))...))
269269
end
270270

271+
filter(f, xs::NamedTuple) = xs[filter(k -> f(xs[k]), keys(xs))]
272+
271273
function merge_names(an::Tuple{Vararg{Symbol}}, bn::Tuple{Vararg{Symbol}})
272274
@nospecialize
273275
@_total_meta

test/namedtuple.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,14 @@ end
134134
@test map(string, (x=1, y=2)) == (x="1", y="2")
135135
@test map(round, (x=UInt, y=Int), (x=3.1, y=2//3)) == (x=UInt(3), y=1)
136136

137+
@testset "filter" begin
138+
@test filter(isodd, (a=1,b=2,c=3)) === (a=1, c=3)
139+
@test filter(i -> true, (;)) === (;)
140+
longnt = NamedTuple{ntuple(i -> Symbol(:a, i), 20)}(ntuple(identity, 20))
141+
@test filter(iseven, longnt) === NamedTuple{ntuple(i -> Symbol(:a, 2i), 10)}(ntuple(i -> 2i, 10))
142+
@test filter(x -> x<2, (longnt..., z=1.5)) === (a1=1, z=1.5)
143+
end
144+
137145
@test merge((a=1, b=2), (a=10,)) == (a=10, b=2)
138146
@test merge((a=1, b=2), (a=10, z=20)) == (a=10, b=2, z=20)
139147
@test merge((a=1, b=2), (z=20,)) == (a=1, b=2, z=20)

0 commit comments

Comments
 (0)