Stream: helpdesk (published)

Topic: findX + return


view this post on Zulip Kevin Bonham (Aug 22 2022 at 20:26):

I know I've asked this before, but probably on slack or something, so I thought I'd ask here for a non-ephemeral answer. I routinely find myself using the pattern collection[find{all|first}(pred, collection)]. That is, I want to find and return the elements of a collection that match some predicate, rather than just the indices.

I'm wondering if there is an existing function that does this in one shot, since often my collection is something that I'm constructing on the fly and then intend to discard.

view this post on Zulip Michael Abbott (Aug 22 2022 at 20:59):

julia> filter(x -> x%10==0, rand(1:100, 30))
4-element Vector{Int64}:
 70
 40
 10
 10

julia> first(Iterators.filter(x -> @show(x%10==0), rand(1:30, 100)))
x % 10 == 0 = false
x % 10 == 0 = true
30

view this post on Zulip Leandro Martínez (Aug 23 2022 at 01:25):

Doesn't

[ val for val in x if val%10 == 0 ]

work as well?

view this post on Zulip Michael Abbott (Aug 23 2022 at 01:43):

Sure. This is syntax for collect(Iterators.filter(...)), and this may be better than my eager filter when "my collection x is something that I'm constructing on the fly" i.e. is probably a Generator

view this post on Zulip Michael Abbott (Aug 23 2022 at 01:45):

My first(...) case could be done more carefully to give say nothing when there are no answers, like findfirst does.

view this post on Zulip Kevin Bonham (Aug 23 2022 at 20:21):

Ahh, filter - of course :derp:

I like the first version using Iterators.filter... that's clever!


Last updated: Dec 28 2024 at 04:38 UTC