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
adddoes not change either vector; it constructs and returns a brand-newVectorfrom the summed components.putstringifies its argument with theStrmethod, so the custom"($.x, $.y)"formatting is what appears.