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.
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
Doesn't
[ val for val in x if val%10 == 0 ]
work as well?
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
My first(...)
case could be done more carefully to give say nothing
when there are no answers, like findfirst
does.
Ahh, filter - of course
I like the first
version using Iterators.filter
... that's clever!
Last updated: Nov 06 2024 at 04:40 UTC