Home > Perl6 > Toying with Time in Perl6

Toying with Time in Perl6

I don’t like S32 much. If it would be a C-lib it would be quite nice. We couldn’t really do much about bad dates anyway.

my $faildate = DateTime.new( '2011-5-31');

Would give use some nice runtime error. That’s a little late. Let’s have some operators to solve that problem.

multi sub infix:<april>(Int $day where { 0 < * < 31 }, Int $year){
  return DateTime.new(:year($year), :month(4), :day($day));
}

multi sub infix:<may>(Int $day where { 0 < * < 32 }, Int $year){
  return DateTime.new(:year($year), :month(5), :day($day));
}

Now we can have some nice syntax.

my DateTime $someday = 1 may 2011;
my DateTime $failday = 30 april 2011;
day of 2011/4 must be in 1..30

  in 'check-value' at line 6915:src/gen/core.pm
  in 'check-date' at line 6923:src/gen/core.pm
  in 'DateTime::new' at line 7050:src/gen/core.pm
  in 'infix:<april>' at line 16:timeling.p6
  in main program body at line 46:timeling.p6

A proper optimiser could evaluate the where-clause at compile time since we supply only (fairly constant) literals.

Time is easy aswell.

multi sub infix:<at>(DateTime $calendary, Int $time where { 0 <= * <= 2400}){ # I'm a little lazy in the where clause here.
  my ($min, $sec) = $time.Str.substr(0, 2).Int, $time.Str.substr(2).Int;

  return DateTime.new($calendary.Instant + ($min * 60 + $sec).Int);
}
my DateTime $meeting = 20 may 2011 at 1530;

A proper return type would be nice too but rakudo doesn’t like –> after a where-clause right now.

Moving the meeting by two weeks wont because rakudo insists on calling the wrong infix:<+>, no matter what I did. I will try again when nom is done. If that would work it would look like.

my DateTime $second_try = $meeting + 2weeks;

Sadly, having a space between 2 and weeks is not possible because Perl6 could not tell the difference between infix:<weeks> and postfix:<weeks>. Still quite neat.

Advertisements
Categories: Perl6
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: