Possible to create class aliases dynamically? - raku

Got this class:
class Mass-lb is Mass {
method new(Rat:D() $value = 1.0) {
self.bless(
:abbr('lb'),
:base_value(453.59237),
:$value,
);
}
}
I have created aliases like this:
class Mass-lbs is Mass-lb { }
class Mass-pound is Mass-lb { }
class Mass-pounds is Mass-lb { }
class Mass-pnds is Mass-lb { }
But I'd prefer to do something like this:
my #lb-syn = < lbs pounds pound pnds >;
for #lb-syn {
EVAL 'class ::("Mass-$_") is Mass-lb {}';
}
This throws an error:
Name ::("Mass-$_") is not compile-time known, and can not serve as a package name
PHP has a built-in for creating aliases: https://www.php.net/manual/en/function.class-alias.php
I couldn't find anything similar for raku.

In RakuAST there's a class that you can call to create a new type. But that the RakuAST branch hasn't landed yet.
Until then, your approach using EVAL is valid, you just need to make it a bit simpler:
class Mass-lb { }
BEGIN "constant Mass-$_ = Mass-lb".EVAL
for <lbs pounds pound pnds>;
my $mlb = Mass-lbs.new;
Make sure the aliases are created at BEGIN time.
No need to subclass, you can use a constant for aliasing.
Since constants are our by default, they're visible outside of the EVAL.

Alternatively, you could use raku Physics::Unit and Physics::Measure...
use Physics::Unit;
use Physics::Measure :ALL;
# define a new custom Unit
Unit.new( defn => 'lbm', names => <Mass-lb Mass-lbs Mass-pound Mass-pounds Mass-pnds> );
say GetUnit('Mass-lbs').names; #[Mass-lb Mass-lbs Mass-pound Mass-pounds Mass-pnds]
# use the Unit in a Measure
my $mass = ♎️'42 Mass-pnds';
say $mass; #42Mass-lb
say $mass.^name; #(..Mass) ...class name
# convert to another Unit
my $kgm = $mass.in: 'kg';
say $kgm; #19.05087954kg
# convert back
say $kgm.in: 'Mass-pound'; #42Mass-lb
# raku Rats mean that the back conversion is identical
say $kgm cmp $mass; #Same
# with % or abs Error
my $mass2 = ♎️'42 Mass-pnds ±3%';
say $mass2; #42Mass-lb ±1.26
say $mass2.in: 'kg'; #19.05087954kg ±0.5715263862
More info at github Physics::Unit and Physics::Measure...

Related

What runtime code can I write to extract the type notations as defined by Sorbet, to display to the user?

Is there a way to inspect the type notations in ruby/sorbet?
I actually want to display those values in a form somewhere and instead of hardcoding in values like "this can be nil or a String", I want to instead use the code I've defined by the sig { ... }.
Example pseudo-code:
class User
extend T::Sig
sig { returns(T.nilable(String)) }
def foo
...
end
end
Sorbet.return_type(User, :instance_method, :foo) # returns '[nil, String]' or similar
I believe this is what I am looking for:
T::Utils.signature_for_method
In action:
T::Utils.signature_for_method(User.new.method(:daily?)).return_type
=> #<T::Types::Union:0x0000000132198da8
#types=[#<T::Types::Simple:0x0000000132198f60 #name="TrueClass", #raw_type=TrueClass>, #<T::Types::Simple:0x0000000132198e98 #name="FalseClass", #raw_type=FalseClass>]>

Perl 6 multi methods never match expected signature

I have a class with two multi methods (multi submit).
I call my multi like this:
$perspective.submit(:message($message.content));
Which gets shipped off to my class:
my $perspective-api = API::Perspective.new(:api-key(%*ENV<PERSPECTIVE_API_KEY>));
proto method submit (|) {*}
multi method submit(Str :$message!, MODEL :#models = TOXICITY) {
my $score = $perspective-api.analyze(:#models, :comment($message));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
multi method submit(Str :$name!, MODEL :#models = TOXICITY) {
my $score = $perspective-api.analyze(:#models, :comment($name));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
}
However I always get the following response:
Died because of the exception:
Cannot resolve caller AUTOGEN(Rose::ContentAnalysis::Perspective:D: :message(Str)); none of these signatures match:
(Rose::ContentAnalysis::Perspective: Str :$message!, MODEL :#models = MODEL::TOXICITY, *%_)
(Rose::ContentAnalysis::Perspective: Str :$name!, MODEL :#models = MODEL::TOXICITY, *%_)
Despite my named argument (:message) being a Str as required and #models having a default declared.
Multiple dispatch works in two phases:
Considering the number of positional parameters and their types
If there are any where clauses, named parameters, or sub-signatures, doing a test bind of the signature to see if it would match
The second phase will reject the candidate if it fails to bind for any reason. One such reason, and I believe the cause of the issue here, is that the default value is wrongly typed. For example, in:
multi m(:#x = "not-an-array") { }
m()
We get an error:
Cannot resolve caller m(...); none of these signatures match:
(:#x = "not-an-array")
in block <unit> at -e line 1
But changing it to:
multi m(:#x = ["an-array"]) { }
m()
Works fine. (Note that while a default value uses =, it's actually a binding, not an assignment.)
In the case in the question there's this:
MODEL :#models = TOXICITY
Looking at the module source the code is taken from, I see:
enum MODEL is export (
<TOXICITY SEVERE_TOXICITY TOXICITY_FAST IDENTITY_ATTACK
INSULT PROFANITY SEXUALLY_EXPLICIT THREAT FLIRTATION
ATTACK_ON_AUTHOR ATTACK_ON_COMMENTER INCOHERENT INFLAMMATORY
LIKELY_TO_REJECT OBSCENE SPAM UNSUBSTANTIAL>
);
Thus TOXICITY is just an Int, but what's expected is a typed array of MODEL values.
Thus, if you do this:
multi method submit(Str :$message!, MODEL :#models = Array[MODEL](TOXICITY)) {
It should work.
I see two issues.
One is that you have two methods that are identical except for the name of one named parameter.
Named parameters can have aliases:
# V--------------V
multi method submit(Str :name(:$message)!, MODEL :#models = TOXICITY) {
my $score = $perspective-api.analyze(:#models, :comment($message));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
}
Note that :$message is really short for :message($message)
Now on the problem which actually prevents your code from working.
#models is a Positional, but you are assigning it a singular value in the signature.
Assign it a Positional, and it works:
(In this case it has to be of type Array[MODEL] because of the MODEL type declaration.)
# V---------------------V
multi method submit(Str :name(:$message)!, MODEL :#models = Array[MODEL](TOXICITY,)) {
my $score = $perspective-api.analyze(:#models, :comment($message));
say #models Z=> $score<attributeScores>{#models}.map: *<summaryScore><value>;
}

Can one perl6 module conditionally 'use' another perl6 module?

Is there a sensible way to have one perl6 module check for the presence of another perl6 module and to 'use' it if and only if it is installed?
Something like this...
module Polygons;
if $available {
use Measure; #only if Measure is installed
}
class Rectangle is export {
has $.width;
has $.height;
method area {
$!width * $!height; #provides operator overload for Measure * Measure
}
}
#====================
module Measure;
class Measure is export {
has $.value;
has $.unit;
method Real {
$!value;
}
method Str {
"$!value $!unit";
}
method multiply( $argument ) {
my $result = $.;
$result.value = $!value * $argument;
$result.unit = "$!unit2";
return $result;
}
}
multi infix:<*> ( Measure:D $left, Measure:D $right ) is export {
return $result.multiply( $argument );
}
#====================
#main.p6
use Polygons;
use Measure;
my $x = Measure.new( value => 10, unit => 'm' );
my $y = Measure.new( value => 20, unit => 'm' );
my $rect = Rectangle.new( width => $x, height => y );
say $rect.area; #'200 m2'
The idea is to propagate the operator overload (infix:<*> in this case) back up the class inheritance so that one store more elaborate objects in the attributes.
(Without tearing up the drains please - since I suspect there is always a way!)
So the first version of this answer was essentially useless.
Here's the first new thing I've come up with that works with what I understand your problem to be. I haven't tried it on the repo yet.
In a file a-module.pm6:
unit module a-module;
our sub infix:<*> ($l,$r) { $l + $r } }
The our means we'll be able to see this routine if we can require it, though it'll only be visible via its fully qualified name &a-module::infix:<*>.
Then in a using file:
use lib '.';
try require a-module;
my &infix:<*> = &a-module::infix:<*> // &OUTER::infix:<*>;
say 1 * 2 # 2 or 3 depending on whether `a-module.pm6` is found
The default routine used if the module is missing can be the one from OUTER (as shown) or from CALLER or whatever other pseudo package you prefer.
This problem/solution seems so basic I suspect it must be on SO or in the doc somewhere. I'll publish what I've got then explore more tomorrow.

Why does this documentation example fail? Is my workaround an acceptable equivalent?

While exploring the documented example raised in this perl6 question that was asked here recently, I found that the final implementation option - (my interpretation of the example is that it provides three different ways to do something) - doesn't work. Running this;
class HTTP::Header does Associative {
has %!fields handles <iterator list kv keys values>;
sub normalize-key ($key) { $key.subst(/\w+/, *.tc, :g) }
method EXISTS-KEY ($key) { %!fields{normalize-key $key}:exists }
method DELETE-KEY ($key) { %!fields{normalize-key $key}:delete }
method push (*#_) { %!fields.push: #_ }
multi method AT-KEY (::?CLASS:D: $key) is rw {
my $element := %!fields{normalize-key $key};
Proxy.new(
FETCH => method () { $element },
STORE => method ($value) {
$element = do given $value».split(/',' \s+/).flat {
when 1 { .[0] } # a single value is stored as a string
default { .Array } # multiple values are stored as an array
}
}
);
}
}
my $header = HTTP::Header.new;
say $header.WHAT; #-> (Header)
$header<Accept> = "text/plain";
$header{'Accept-' X~ <Charset Encoding Language>} = <utf-8 gzip en>;
$header.push('Accept-Language' => "fr"); # like .push on a Hash
say $header<Accept-Language>.perl; #-> $["en", "fr"]
... produces the expected output. Note that the third last line with the X meta-operator assigns a literal list (built with angle brackets) to a hash slice (given a flexible definition of "hash"). My understanding is this results in three seperate calls to method AT-KEY each with a single string argument (apart from self) and therefore does not exersise the default clause of the given statement. Is that correct?
When I invent a use case that excersises that part of the code, it appears to fail;
... as above ...
$header<Accept> = "text/plain";
$header{'Accept-' X~ <Charset Encoding Language>} = <utf-8 gzip en>;
$header{'Accept-Language'} = "en, fr, cz";
say $header<Accept-Language>.perl; #-> ["en", "fr", "cz"] ??
# outputs
(Header)
This Seq has already been iterated, and its values consumed
(you might solve this by adding .cache on usages of the Seq, or
by assigning the Seq into an array)
in block at ./hhorig.pl line 20
in method <anon> at ./hhorig.pl line 18
in block <unit> at ./hhorig.pl line 32
The error message provides an awesome explanation - the topic is a sequence produced by the split and is now spent and hence can't be referenced in the when and/or default clauses.
Have I correctly "lifted" and implemented the example? Is my invented use case of several language codes in the one string wrong or is the example code wrong/out-of-date? I say out-of-date as my recollection is that Seq's came along pretty late in the perl6 development process - so perhaps, this code used to work but doesn't now. Can anyone clarify/confirm?
Finally, taking the error message into account, the following code appears to solve the problem;
... as above ...
STORE => method ($value) {
my #values = $value».split(/',' \s+/) ;
$element = do given #values.flat {
when 1 { $value } # a single value is stored as a string
default { #values } # multiple values are stored as an array
}
}
... but is it an exact equivalent?
That code works now (Rakudo 2018.04) and prints
$["en", "fr", "cz"]
as intended. It was probably a bug which was eventually solved.

Access Instance-property in Coffeescript within nested

so I am using express within a node-app. As my app is getting bigger I want to put my routes into extra files. I seem to be able to get hold of the bugDB if I just get rid of the intermediate get object. But I can't access the bugDB in the inner object. Any suggestions? Maybe there is even a more nice code pattern for how to accomplish this more elegantly.
I would appreachate your help. Thanks in advance. (As I am not a native speaker I couldn't find others with a similar problem, if you know how to phrase the question better, please show me the way :) )
BUGROUTER.COFFEE
class BugsRouter
constructor: (#bugDB)-> // instance-variable with databaselink
return
get:{
allBugs: (req, res)=>
console.log "db", #bugDB // this gives me undefined
// is "this" in the get context?
#bugDB.allDocs {include_docs: true}, (err, response)->
res.json 200, response
}
module.exports = BugsRouter
SERVER.COFFEE
BugsRouter = require "./routes/BUGROUTER"
bugsRouter = new BugsRouter(bugDB)
console.log bugsRouter.bugDB # this is working
app.get "/bugs/all", bugsRouter.get.allBugs
Sub-objects don't work like that. When you say this:
class C
p:
f: ->
Then p is just a plain object that happens to be a property on C's prototype, it will have no special idea of what # should be inside f. And if you try to use a fat-arrow instead:
class C
p:
f: =>
then you're accidentally creating a namespaced class function called f so # will be C when f is called. In either case, saying:
c = new C
c.p.f()
is the same as:
c = new C
p = c.p
p.f()
so f will be called in the context of p rather than c.
You can get around this if you don't mind manually binding the functions inside get when your constructor is called:
constructor: (#bugDB) ->
#get = { }
for name, func of #constructor::get
#get[name] = func.bind(#)
This assumes that you have Function.bind available. If you don't then you can use any of the other binding techniques (_.bind, $.proxy, ...). The #get = { } trick is needed to ensure that you don't accidentally modify the prototype's version of #get; if you're certain that you'll only be creating one instance of your BugsRouter then you could use this instead:
constructor: (#bugDB) ->
for name, func of #get
#get[name] = func.bind(#)
to bind the functions inside the prototype's version of get rather than the instance's local copy.
You can watch this simplified demo to see what's going on with # in various cases, keep an eye on the #flag values to see the accidental prototype modification caused by not using #get = { } and #constructor::get:
class C1
get:
f: -> console.log('C1', #)
class C2
get:
f: => console.log('C2', #)
class C3
constructor: ->
#flag = Math.random()
for name, func of #get
#get[name] = func.bind(#)
get:
f: -> console.log('C3', #)
class C4
constructor: ->
#flag = Math.random()
#get = { }
for name, func of #constructor::get
#get[name] = func.bind(#)
get:
f: -> console.log('C4', #)
for klass in [C1, C2, C3, C3, C4, C4]
o = new klass
o.get.f()
Live version of the above: http://jsfiddle.net/ambiguous/8XR7Z/
Hmm, seems like I found a better solution after all:
class Test
constructor: ->
#testVariable = "Have a nice"
return
Object.defineProperties #prototype,
get:
enumerable :true
get:->
{
day: => #testVariable + " day"
week: => #testVariable + " day"
}
console.log (new Test()).get.day()
This allows me to call (new Test()).get.day() the way I wanted.
Live version at: JSFiddle