extend reduce_empty to more operators and types
#48926
Open
+58
−19
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
One can reasonably define an empty reduction
reduce(op, T[])whenever there is a neutral element for the operatoropwith arguments inT. This PR adds such cases that are currently not defined. Maybe you like some or all of them.At present
&and|are only defined forBool, andxornot at all. I extend these operators to allIntegertypes, includingBigInt. The definition-1 % TI have chosen is equivalent to~zero(T)for all existing types, but makes fewer allocations forBigInt.I also define the neutral elements for
minandmaxto betypemax(T)andtypemin(T). (This works even for theminormaxwithNaN.) I also extendextremato work with empty lists.I can see two concerns one could raise. (Maybe there are others.)
In some cases, the neutral elements do not behave well with respect to conversions to larger types. For example, while for
T <: Signedone consistently getsreduce(&, T[]) == -1, the result for an unsigned bit integer typeTistypemax(T). However, here one might argue that one already has the same problem with arithmetic operations in case of overflow.@timholy made changes to
reduce_emptyin f2dcc44 to avoid method invalidations. I don't know how my PR affects this. If it is a problem, I'm hoping that one can avoid it by definingreduce_emptyforminandmaxonly for certain types, for exampleT <: Real. (There are other types that definetypeminand/ortypemax, for exampleChar,DateandString.)