In Raku: when I create an object with a CALL-ME method, I would like to use the < ... >
syntax for the signature instead of ( '...' )
when ...
is a Str.
In the documentation, there is an example of creating an operator, which is an ordinary Raku sub with a special syntax. This sort of sub automatically converts < ... >
into a Str.
For example, if I have
use v6.d;
class A {
has %.x;
method CALL-ME( Str:D $key ) { say %!x{ $key } }
}
my A $q .= new( :x( <one two three> Z=> 1..* ) );
$q('two');
$q<two>;
But this produces
2
Type A does not support associative indexing.
in block <unit> at test.raku line 10
3
1 Answer
An answer based on @raiph’s comment:
You need to implement the AT-KEY
method on your type.
You can do so directly like this:
class A {
has %.x;
method CALL-ME( Str:D $key ) { say %!x{ $key } }
method AT-KEY($key) { self.($key) }
}
Or you can do so by delegating AT-KEY
to %!x
using the handles
trait:
class A {
has %.x handles <AT-KEY>;
method CALL-ME( Str:D $key ) { say %!x{ $key } }
}
4
-
@raiph but if I'm reading the reddit thread correctly, neither your AJS's suggested change nor yours would change the semantics of
handles <AT-KEY>
, would they? (It's just abouthandles *
orhandles '*'
, right?)– codesections13 hours ago
-
In the question, I used
has %.x
as the minimal structure. In the code I'm working on, the hash does exist a couple of layers down, so ahandles
is not really an option. The method AT-KEY is the more generic route.– Richard Hainsworth12 hours ago
-
@codesections Correct.
– raiph11 hours ago
-
@codesections My current understanding is that an explicit
method AT-KEY
(as Richard has chosen to go with) is problematic, addinghandles <AT-KEY>
(explicitly delegating) is problematic, andhandles *
(which is trumped not only by methods in the enclosing class but also classes it inherits from) is problematic. That's why I was hesitant to write an answer. But having figured out enough to feel my comment link plus an answer abouthandles <AT-KEY>
would be enough to help while I worked to nail down the problems and write a nuanced answer, I posted my answer — and then saw yours. 👍 🙃– raiph11 hours ago
cf Something is wrong with handles.
16 hours ago
Changing
has %.x;
tohas %.x handles <AT-KEY>;
means your example works. This follows logically from Liz's comment in the discussion I linked. But, based on what AJS said in that thread, I imply no warranties on the general fitness of this solution.15 hours ago
@raiph, the r/rakulang thread is closed, but I agree with what you said there about
class Foo is Hash
. Thenew
issue can be solved withmethod new(|c) { self.Any::new(|c) }
14 hours ago