A few ideas:
- A few enums could make sense in this situation, depending on what syntax you are aiming for
- I'm not sure that you need to specify the associativity and precedence when they are the same as the default for those operations
- A postcircumfix operator would allow you to send things like 'kg' as a parameter
- I'm not sure you need to list the submethod BUILD since it behaves like the default
- You can avoid some redundancy in defining your operators if Mass and Length have a common ancestor
Here's another version that accomplishes something similar:
enum Prefixes (
:pico(10.0 ** -12), :nano(10.0 ** -9), :micro(10.0 ** -6),
:milli(10.0 ** -3),
:centi(10.0 ** -2), :one(1.0), :hecto(10.0 ** 2),
:kilo(10.0 ** 3),
:mega(10.0 ** 9), :giga(10.0 ** 9), :tera(10.0 ** 12),
);
enum MassAbbrevs (
:g(one),
:kg(kilo)
);
enum LengthAbbrevs (
:m(one),
:km(kilo)
);
class SI { }
class Mass is SI {
has $.v;
}
class Length is SI {
has $.v;
}
multi postcircumfix:<[ ]>(Real $n, MassAbbrevs $abbrev ) {
return Mass.new(v => $n * $abbrev);
}
multi postcircumfix:<[ ]>(Real $n, LengthAbbrevs $abbrev ) {
return Length.new(v => $n * $abbrev);
}
multi infix:<+>( SI $x , SI $y where .isa($x) ) {
$x.WHAT.new( v => $x.v + $y.v);
}
say 10[kg] + 1[g];
say 1[km] + 1[m];
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.