I often find that I want to use something like
findfirst on iterables that have no (or inefficient) random access, something like
function satisfies_first(predicate, itr)
for i in itr
predicate(i) && return Some(i)
julia> satisfies_first(iseven ∘ first, ((i, 2*i) for i in 1:10))
It is pretty trivial to code this, but does this exist in a package somewhere? Or
Base? I found this discussion about something similar, but I want to be careful about corner cases (element not found).
Possibly just chain
Iterators.filter(==(5), [1 2 3 4 5]) |> x -> isempty(x) ? nothing : first(x)?
Sure, but that’s quite a mouthful for something so basic (and also note that it should give back
I will wait for more replies, then consider contributinga function not unlike the above to
Maybe a bit nicer:
itr = ((i, 2i) for i in 1:10)
predicate = isodd ∘ first
But this breaks if the collection is empty (there is no first to collect). Yea, nm. I’ll post this anyways…
I would perhaps define the generally useful
ϕ = iterate(iter)
ϕ === nothing && return nothing
instead and then it becomes
you stay a bit longer in the “iterator-world”
People seemed open to the idea of adding that kind of functionality to Base, but I didn’t pursue it through until the PR was merged.