Course of Raku / Objects, I/O, and exceptions / Classes and objects / Attributes / Exercises / A point class
Solution: A point class
Here is a possible solution to the task.
Code
class Point {
has $.x;
has $.y;
}
my $a = Point.new(x => 3, y => 4);
my $b = Point.new(x => 0, y => 0);
my $dist = sqrt(($a.x - $b.x) ** 2 + ($a.y - $b.y) ** 2);
say $dist;🦋 You can find the source code in the file point-class.raku.
Output
5Comments
The two
has $.xandhas $.ydeclarations create the attributes together with their read accessors.Each object stores its own
xandy, so$aand$breport different coordinates even though they are the same kind of object. This independence is the whole point of attributes — each instance carries its own data.
Course navigation
← A point class | A counter →