January 2015 Archives

Can you provide an x/y Point class in other languages?

Update: Thanks for all of the replies. However, I now need to block further replies due to the huge amount of spam this post is getting.

I'm writing a talk for Fosdem entitled "Perl 6 -- A Dynamic Language for Mere Mortals." The talk is about Perl 6 and is aimed at programmers, not just Perl devs. As a result, I'd love to find examples in Java, Python, Ruby, and so on, which are roughly equivalent to the following Perl 6 class.

class Point {
  subset PointLimit of Real where -10 <= * <= 10;
  has PointLimit $.x is rw = 0;
  has PointLimit $.y is rw = 0;
  method Str { "[$.x,$.y]" }
}

That class lets you do something like this:

my $point = Point.new( x => 5, y => 3.0 );
say "$point";                             # [5,3]
$point.y = 17.3;                          # Boom!

In other words, both X and Y are real numbers constrained between -10 and 10, inclusive, and overloads stringification. What follows are two roughly equivalent implementations in Perl 5.

About Ovid

user-pic Freelance Perl/Testing/Agile consultant and trainer. See http://www.allaroundtheworld.fr/ for our services. If you have a problem with Perl, we will solve it for you. And don't forget to buy my book! http://www.amazon.com/Beginning-Perl-Curtis-Poe/dp/1118013840/