How to get the `< ... >` syntax on an object?
Asked Answered
C

1

10

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
Cissoid answered 12/11, 2023 at 16:24 Comment(3)
cf Something is wrong with handles.Boru
Changing has %.x; to has %.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.Boru
@raiph, the r/rakulang thread is closed, but I agree with what you said there about class Foo is Hash. The new issue can be solved with method new(|c) { self.Any::new(|c) }Someplace
S
9

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 } }
}
Someplace answered 12/11, 2023 at 20:46 Comment(3)
@Boru 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 about handles * or handles '*', right?)Someplace
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 a handles is not really an option. The method AT-KEY is the more generic route.Cissoid
@Someplace Correct.Boru

© 2022 - 2024 — McMap. All rights reserved.