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:
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)
raising to power
Implemented traits
AnyType
,
UnknownDestructibility
Aliases
__del__is_trivial
alias __del__is_trivial
A flag (often compiler generated) to indicate whether the implementation of __del__
is trivial.
The implementation of __del__
is considered to be trivial if:
- The struct has a compiler-generated trivial destructor and all its fields
have a trivial
__del__
method.
In practice, it means that the __del__
can be considered as no-op.
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:
_Self
: The value of self
raised to the power of exp
.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!