Skip to content

Built-in power function #10387

@PgBiel

Description

@PgBiel

Is your feature request related to a problem? Please describe.
Some rather simple and not so uncommon operations involve raising a number to a certain power. One example is for bitwise operations: bit shifting (multiplying or dividing by powers of 2), bit masking (which uses shifting) - useful e.g. when dealing with UTF-8 or other similar types of data; and so on - those would be use cases for int ^ int operations (using an informal ^ notation for power). But float ^ float operations are also useful at times, e.g. to calculate the square root of a number (x ^ 0.5), which can be used whenever you need to work with things like distances, or you need to "revert" some power operation (among other possibilities).

However, those operations are not currently available and require manual implementation, which is simple for int ^ int (albeit likely slower than a native solution when used repeatedly with slightly larger exponents), but not so simple for float ^ float.

Describe the solution you'd like
I think something like builtins.pow x y would be nice. When x and y are both ints with y >= 0, an int is returned. When y is negative or one of them is a float (or both are), a float is returned. (Or something similar to that.)

We'd also have to handle the x == y == 0 case somehow, as well as attempts to calculate roots of negative numbers. In principle, throwing an error is a possibility.

Describe alternatives you've considered
You can currently implement int ^ int in pure Nix with recursion or by multiplying an entire list where the base is repeated exponent times. However, that does feel like some unnecessary overhead for this operation, which is often repeated many times when it's needed. Additionally, float ^ float wouldn't be as simple to implement (requiring some extra math) and would likely have more overhead. It feels like adding a fast, native and globally available function for power wouldn't harm the language, and would be overall positive.

Additional context
(none)

Priorities

Add 👍 to issues you find important.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureFeature request or proposallanguageThe Nix expression language; parser, interpreter, primops, evaluation, etc
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions