Skip to content

proposal: math: Reflect, Least, GreatestΒ #60274

Open
@jimmyfrasche

Description

@jimmyfrasche
package math

func Reflect[T Number]() Kind
type Kind uint
func (Kind) Size() int
func (Kind) Ordered() bool
func (Kind) Float() bool
func (Kind) Complex() bool
func (Kind) Signed() bool
func (Kind) Unsigned() bool
func (Kind) Integer() bool

func Least[T Ordered]() T
func Greatest[T Ordered]() T

func Convert[S, T Number](T) (S, bool)

Reflect returns a Kind bitset that provides information about the properties of a numeric type. The bool returning methods correspond with the constraints and Size returns 8, 16, etc. Since this is about the properties of the type not its identity Reflect[int]() == Reflect[int64]() on platforms where int is 64 bits.

Least (Greatest) return the element that is <= (>=) every element in T. For example, Greatest[float64]() is math.Inf(0), Least[uint]() is 0, and Greatest[int16] is math.MaxInt16.

Convert performs the conversion between numeric types S and T and the boolean reports whether the conversion was lossless, returning false if there was any truncation or wrapping.

Future versions of the language may allow Reflect to be written using type switches but this would still provide a more convenient interface.


For convenience, I've assumed #52427 is accepted and that Unsigned, Signed, Integer, Float, and Complex have been moved into package math.

I have also assumed that these additional constraints are defined:

type Ordered Integer | Float
type Number Ordered | Complex

The Ordered constraint is similar to that in package cmp except that it does not include ~string. The package qualification should be sufficient to disambiguate.

If this api is too much or too different for math, it, and all the constraints, could go into a new package, math/number or the like.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions