Skip to main content

Mojo trait

Powable

The Powable trait describes a type that defines a power operation (i.e. exponentiation) with the same base and exponent types.

Types that conform to Powable will work with the builtin pow function, which will return the same type as the inputs.

For example:

@value
struct Rational(Powable):
var numerator: Float64
var denominator: Float64

fn __init__(out self, numerator: Float64, denominator: Float64):
self.numerator = numerator
self.denominator = denominator

fn __pow__(self, exp: Self) -> Self:
var exp_value = exp.numerator / exp.denominator
return Self(pow(self.numerator, exp_value), pow(self.denominator, exp_value))
@value
struct Rational(Powable):
var numerator: Float64
var denominator: Float64

fn __init__(out self, numerator: Float64, denominator: Float64):
self.numerator = numerator
self.denominator = denominator

fn __pow__(self, exp: Self) -> Self:
var exp_value = exp.numerator / exp.denominator
return Self(pow(self.numerator, exp_value), pow(self.denominator, exp_value))

You can now use the ** operator to exponentiate objects inside generic functions:

fn exponentiate[T: Powable](base: T, exp: T) -> T:
return base ** exp

var base = Rational(Float64(3.0), 5.0)
var exp = Rational(Float64(1.0), 2.0)
var res = exponentiate(base, exp)
fn exponentiate[T: Powable](base: T, exp: T) -> T:
return base ** exp

var base = Rational(Float64(3.0), 5.0)
var exp = Rational(Float64(1.0), 2.0)
var res = exponentiate(base, exp)
raising to power
raising to power

Implemented traits

AnyType

Methods

__pow__

__pow__(self: _Self, exp: _Self) -> _Self

Return the value raised to the power of the given exponent.

Args:

  • exp (_Self): The exponent value.

Returns:

The value of self raised to the power of exp.