Skip to content

Dispatchable representations for one and zero #41853

@oschulz

Description

@oschulz

My apologies in case this has been suggested before: I propose to add types One <: Integer and Zero <: Integer to the language (or some other dispatchable representation, see below).

We currently do have dispatchable, precision-independent representations for (e.g.) π and , and the concept has worked very well. I would argue that one and zero are even more fundamental concepts, and there should be a resolution-independent and dispatchable representation for them.

A nice prototype by @perrutquist exisits (https://github.com/perrutquist/Zeros.jl) - but in the end, this can't really be done outside of Base without type piracy (so Zeros.jl needs Zeros.@pirate Base).

Instead of separate types for one and zero we could, of course, also have something like IntegerVal{1} and IntegerVal{0}, similar to Irrational.

Having a dispatchable one and zero would allow for zero-memory arrays fill with one and zero, eliminating the need for constructs like FillArrays.Ones (one would simply use Fill(One(), n), CC @mcabbott, @dlfivefifty).

In addition, there would be a lot of potential for automatic and specialization-based code optimization. Statistics code that supports weights would run the same speed for One() weights as the unweighted version of the algorithm, while offering a single generic user interface, and so on (CC @nalimilan, @andreasnoack).

One could also dispatch on things like Distributions.Normal(Zero(), One()) for optimized code (CC @devmotion, could be very useful for prior transformations to standard normal and such).

Also concepts like one- and zero-valued gradients/tangents could profit from having a native, dispatchable one and zero (CC @oxinabox).

Also relates to #41840 (CC @mkitti): Having One and Zero would also very elegantly allow for

(::Colon)(::Zero, n) = Base.ZeroTo(n)
(::Colon)(::One, n) = Base.OneTo(n)

(We could add Base.ZeroTo at the same time, would be nice to have anyway.)

one and zero would continue to serve as ways to handle type/precision-specific ones and zeros.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions