Special methods for structs
Context
- Mojo Manual: Structs - Special Methods
- Mojo Version: 24.2.0
Demo: Defining a Dual Number struct
This demo showcases the creation of a struct to represent Dual Numbers, which are numbers of the form a+b系
, where a
and b
are real numbers, and 系
is a special element with the property 系 * 系 = 0
yet 系 in not 0.
Addition and multiplication for dual numbers are defined as:
(a+b系) + (c+d系) = a+b + (c+d)系
(a+b系) * (c+d系) = a*b + (a*c+b*d)系
To implement this arithmetic for our struct, we can use the special methods __add__()
and __mul__()
. Further arithmetic operations could be implemented in a similar way. (See the Int description in the Mojo documentation to learn about the names of the respective special functions in Mojo). Here, we also implement the special method __str__()
which returns a string representation of a dual number. By implementing this method, the struct conforms to the Stringable trait and can be used in print statements.
|
|
Output:
(2.0 + 3.0系) + (1.0 + 4.0系) = (3.0 + 7.0系)
(2.0 + 3.0系) * (1.0 + 4.0系) = (2.0 + 11.0系)
Remarks
Mojo supports a long list of special methods (also called dunder methods) which generally match all of Python’s special methods: https://docs.python.org/3/reference/datamodel.html#special-method-names