Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support Whatever ranges in multidimensional subscript access with AT-POS

Tags:

raku

How can I implement AT-POS such that it supports multidimensional Whatever ranges, like [0;*] and [*;0]?

In the implementation below, I get Index out of range errors:

class Foo {
    has @.grid;
    multi method elems { @!grid.elems }
    multi method AT-POS($y, $x) is rw { @!grid[ $y ; $x ] }
    multi method ASSIGN-POS ($y, $x, $new) { @!grid[ $y; $x ] = $new }
    multi method EXISTS-POS($y, $x) { @!grid[ $y; $x ]:exists }
}

my $foo = Foo.new: :grid[ ['a'], ['b', 'c'] ];
say $foo[0;0];         # a
say $foo[0;*].elems;   # Expect 1, get 2
say $foo[0;*];         # Expect (a), get "Index out of range"
say $foo[*;0];         # Expect (a b), get "Index out of range"
like image 813
randy Avatar asked Aug 01 '20 21:08

randy


1 Answers

The doc says the API is AT-POS($index).

When I replace your AT-POS with:

    multi method AT-POS($index) is rw { @!grid[ $index ] }

your test cases give the results you expect.

Your ASSIGN-POS is unnecessary and may make things go wrong.

like image 85
raiph Avatar answered Oct 25 '22 11:10

raiph