Special methods for structs

Context


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.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct DualNumber(Stringable):
    var real:Float64
    var dual:Float64 

    fn __init__(inout self,real:Float64=0,dual:   Float64=0):
        self.real = real
        self.dual = dual 

    fn __add__(self,other:Self) -> Self :
        return Self(self.real+other.real,self.dual+other.dual)

    fn __mul__(self,other:Self) -> Self :
        return Self(self.real*other.real,self.real*other.dual+self.dual*other.real)

    fn __str__(self) -> String:
        return "(" + str(self.real) + ' + ' + str(self.dual) + "系)"

fn main():

    var a = DualNumber(2,3)
    var b = DualNumber(1,4)

    print(a,'+',b,'=',a+b)
    print(a,'*',b,'=',a*b)

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