Skip to content

Instantly share code, notes, and snippets.

@Xliff
Created August 12, 2021 11:11
Show Gist options
  • Save Xliff/a09d103689cd03f2241b04d63fa905bb to your computer and use it in GitHub Desktop.
Save Xliff/a09d103689cd03f2241b04d63fa905bb to your computer and use it in GitHub Desktop.
EXPORT made easy?
use v6;

package Bizzell::Operators {

  multi sub postfix:<seconds> ($a) {
    $a;
  }

  multi sub postfix:<minutes> ($a) {
    $a * 60;
  }

  multi sub postfix:<hours> ($a) {
    $a * 3600 * 3600
  }

  multi sub postfix:<days> ($a)  {
    $a * 86400;
  }

}

sub EXPORT {
  Map.new(
    '&postfix:<seconds>' => &Bizzell::Operators::postfix:<seconds>,
    '&postfix:<s>'       => &Bizzell::Operators::postfix:<seconds>,

    '&postfix:<minutes>' => &Bizzell::Operators::postfix:<minutes>,
    '&postfix:<m>'       => &Bizzell::Operators::postfix:<minutes>,

    '&postfix:<hours>'   => &Bizzell::Operators::postfix:<hours>,
    '&postfix:<h>'       => &Bizzell::Operators::postfix:<hours>,

    '&postfix:<days>'    => &Bizzell::Operators::postfix:<days>,
    '&postfix:<d>'       => &Bizzell::Operators::postfix:<days>
  )
}

Now getting the basics of this is easy. I could add "is export" to the definitions in Bizzell::Operators and call it a day, but what would be the easy way of adding the associated aliases that would make this expression:

4days + 8hours + 10minutes - 1second

Turn into the much more elegant:

4d + 8h + 10m - 1s

BTW -- the above does NOT work.

@Xliff
Copy link
Author

Xliff commented Aug 12, 2021

In the end, this is the EXPORT declaration that worked:

sub EXPORT {
  my %EXPORT;

  %EXPORT{'&postfix:<s>'}       :=
    Bizzell::Operators::EXPORT::DEFAULT::{'&postfix:<seconds>'};
  %EXPORT{'&postfix:<m>'}       :=
    Bizzell::Operators::EXPORT::DEFAULT::{'&postfix:<minutes>'};
  %EXPORT{'&postfix:<h>'}       :=
    Bizzell::Operators::EXPORT::DEFAULT::{'&postfix:<hours>'};
  %EXPORT{'&postfix:<d>'}       :=
    Bizzell::Operators::EXPORT::DEFAULT::{'&postfix:<days>'};

  %EXPORT.Map;
}

@Xliff
Copy link
Author

Xliff commented Aug 12, 2021

Of course, leave it to the wonderful lizmat++ to come up with a better (non-dynamic) solution:

our sub postfix:<days> ($a) { 
 $a * 86400;
}
our &postfix:<d> := &postfix:<days>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment