extend reduce_empty
to more operators and types
#48926
Open
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 operatorop
with 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
, andxor
not at all. I extend these operators to allInteger
types, includingBigInt
. The definition-1 % T
I have chosen is equivalent to~zero(T)
for all existing types, but makes fewer allocations forBigInt
.I also define the neutral elements for
min
andmax
to betypemax(T)
andtypemin(T)
. (This works even for themin
ormax
withNaN
.) I also extendextrema
to 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 <: Signed
one consistently getsreduce(&, T[]) == -1
, the result for an unsigned bit integer typeT
istypemax(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_empty
in 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_empty
formin
andmax
only for certain types, for exampleT <: Real
. (There are other types that definetypemin
and/ortypemax
, for exampleChar
,Date
andString
.)