For v0.7 the find
functions return nothing
when no match is found.
Would it be convenient to provide a default parameter to return if no match is found, similar to the get
function?
For example:
findlast(!iszero, A, 0)
would return 0 if there is no match.
(then effectively findlast(pred, A) = findlast(pred, A, nothing)
2 Likes
Seems like you could define a similar one line function that does what you want. If the base function returns nothing, you set it to the extra parameter.
2 Likes
The issue with that would be efficiency.
For strings, for example, where any valid index is guaranteed to be > 0, using 0 for the sentinel can be more efficient than returning nothing
, and then to have to test for nothing
just to turn it back into a 0
, seems sad.
(esp. since some of the internal code in base actually returns 0, and then checks for that,
and returns nothing
instead!)
Well of course I can define my own methods, but my question was would this be more widely useful.
Is so, there could be a standard implementation in Base, which would obviate separate custom implementations and promote idiomatic use.
In any case, here’s what I’ve defined for my purpose:
v0.6
Base.findlast(pred::Function, A, default) =
(i = findlast(pred, A); i in linearindices(A) ? i : default)
v0.7
Base.findlast(pred::Function, A, default) =
(i = findlast(pred, A); i == nothing ? default : i)
And similarly for other find
functions.