3.days.ago implementation in Perl6

I want to implement a time calculation, for example 3.days.ago and 2.months.from_now . Is it possible to extend a method to Int, or can overriding an operator do this?

 1.day.ago # equivalent to yesterday 1.day.from_now # equivalent to tomorrow 
+5
source share
3 answers

To get what you ask for:

 use MONKEY-TYPING; augment class Int { my class Date::Offset { has Pair $.offset is required; method ago () { Date.today.earlier( |$!offset ) } method from-now () { Date.today.later( |$!offset ) } } method days () { Date::Offset.new( offset => days => self ); } method months () { Date::Offset.new( offset => months => self ); } } say 1.days.ago; # 2017-03-13 say Date.today; # 2017-03-14 say 1.days.from-now; # 2017-03-15 say 1.months.ago; # 2017-02-14 

Now that I have shown you how, please, do not. You can end up affecting code that you did not intend, in a way that is very difficult to fix.
(There are legitimate reasons to do something similar, but I don't think this is one of them)

If you want to spoil the basic actions, do it lexically.

 { sub postfix:ยซ .days.ago ยป ( Int:D $offset ) { Date.today.earlier( days => $offset ) } sub postfix:ยซ .days.from-now ยป ( Int:D $offset ) { Date.today.later( days => $offset ) } sub postfix:ยซ .months.ago ยป ( Int:D $offset ) { Date.today.earlier( months => $offset ) } sub postfix:ยซ .months.from-now ยป ( Int:D $offset ) { Date.today.later( months => $offset ) } say 1.days.ago; # 2017-03-13 say Date.today; # 2017-03-14 say 1.days.from-now; # 2017-03-15 say 1.months.ago; # 2017-02-14 } say 1.days.ago; # error 
+7
source

The main way to expand an existing class is to increase it:

 use MONKEY-TYPING; augment class Int { method day() { "day" } } say 42.day 

From there, you can create a day method to create an object that can handle the back and from_now methods.

Remember that it seems to you that you need to think a little about your API: the first line seems to be using day today. Today, the second line contains only "from_now".

Note that at the moment, subclasses are not aware of padded superclasses: this is a known issue. The only way that is currently being done is to recompile the subclasses you need after increasing their superclass:

 use MONKEY-TYPING; augment class Cool { # Int is a subclass of Cool method day() { "day" } } BEGIN Int.^compose; # make sure Int knows about ".day" say 42.day 
+7
source

This might be interesting for use MONKEY-TYPING , but if you just want to calculate dates, then just use the built-in Date object:

 put Date.today; # 2017-03-23 put Date.today.earlier(day=>3); # 2017-03-20 put Date.today.later(month=>3); # 2017-06-23 

(I know about trying smart syntax , but I'm glad he talked about it ).

+5
source

Source: https://habr.com/ru/post/1265411/


All Articles