golang/go

proposal: go/math: add generic numeric utilities

Closed this issue · 2 comments

Proposal Details

Abstract

This proposal suggests extending the existing math package to include generic versions of common mathematical functions such as Min, Max, Clamp, and potentially others, using Go’s type parameters (generics).

The goal is to modernize the math package by leveraging generics introduced in Go 1.18, improving usability and reducing repetitive code while maintaining full backward compatibility with existing APIs.


Background

The current math package operates exclusively on the float64 type. This design made sense before Go 1.18, but it limits reusability when developers need similar functionality for other numeric types (int, uint, float32, etc.).

As a result, developers often reimplement simple functions like Min, Max, or Clamp for other numeric types. This leads to boilerplate code and inconsistency across projects.

With the introduction of generics and the constraints package, it’s now feasible to write type-safe, efficient, and reusable numeric functions directly within the math package itself.


Proposal

Extend the math package by introducing generic equivalents for certain mathematical functions.

For example:

package math

import "golang.org/x/exp/constraints"

// Min returns the smaller of a or b.
func Min[T constraints.Ordered](a, b T) T {
    if a < b {
        return a
    }
    return b
}

// Max returns the larger of a or b.
func Max[T constraints.Ordered](a, b T) T {
    if a > b {
        return a
    }
    return b
}

// Clamp limits a value v to the range [min, max].
func Clamp[T constraints.Ordered](v, min, max T) T {
    if v < min {
        return min
    }
    if v > max {
        return max
    }
    return v
}

min and max are builtins now.
does that just leave clamp?

clamp can just be written as a combination of the min and max builtins
I didn't see anything further to do.