arraysrakumatrix-indexingarrayaccess

Is there subscript syntax to extract a diagonal from a 2D Array?


I mostly can follow the syntax to 'drill down/slice' into an array with multiple dimensions (and flattening) on the docs page. A very cool feature. For example given:

my @a=[[1,2,3],
       [4,5,6],
       [7,8,9]];

I can select column 2 of the above using:

say @a[0,1,2;1]; #This output (2,5,8)

Is it possible to extract the diagonal (1,5,9) in a similar compact syntax?


Solution

  • say @a[ 0,1,2 ; { $++ } ] ; # (1 5 9)
    

    So instead of 1, which evaluates to 1, I've used { $++ }, which is a Block.

    When Raku encounters a callable code object as a subscript value, it calls it once for each slice it's evaluating, in this case the 0th, 1st, and 2nd rows.

    $ is an anonymous Scalar state variable.