Course of Raku / Addendum 🆕 / Types and text machines / Objects and classes / Exercises / Adding vectors

Solution: Adding vectors

Here is a possible solution to the task.

Code

class Vector {
    has $.x;
    has $.y;

    method add(Vector $v) {
        Vector.new(x => $.x + $v.x, y => $.y + $v.y);
    }

    method Str { "($.x, $.y)" }
}

my $sum = Vector.new(x => 1, y => 2).add(Vector.new(x => 3, y => 4));

put $sum;

🦋 You can find the source code in the file vector-add.raku.

Output

(4, 6)

Comments

  1. add does not change either vector; it constructs and returns a brand-new Vector from the summed components.

  2. put stringifies its argument with the Str method, so the custom "($.x, $.y)" formatting is what appears.

Course navigation

Adding vectors   |   Animals that speak