Question

I tried using an array to specify an index of a 2-dimensional array, but the pick function won't accept an array as the second element:

print pick [[3 5] [3 1]] [2 1]

*** ERROR
** Script error: invalid argument: [2 2]
** Where: pick try do either either either -apply-
** Near: pick [[3 5] [3 1]] [2 2]

I found a workaround for this, but it's slightly more verbose:

print pick pick [[3 5] [3 1]] 2 1
[comment This prints "3".]

Is it possible to access an index of a multidimensional array without calling the pick function multiple times?

Was it helpful?

Solution

A more succinct way to PICK out an element from a multi-dimensonal array is to use the PATH! syntax.

Here's an example in the Rebol console:

>> x: [[3 5] [3 1]]     
== [[3 5] [3 1]]

>> x/2/1
== 3

>> x/2/2                      
== 1

>> x/1/(1 + 1)      ;; use parens for expressions - transforms to x/1/2
== 5

>> p: 2
== 2

>> x/1/:p           ;; use ":" for variable reference - transforms to x/1/2 
== 5

>> x/(p - 1)/:p     ;; mix and match at any level of array - transforms to x/1/2
== 5    

>> x/3              ;; NONE is returned if index does not exist
== none

>> x/2
== [3 1]

>> x/2/3            ;; again out of range
== none

Another alternative would be the FIRST, SECOND .. TENTH functions:

>> second first [[3 5] [3 1]] 
== 5

You can even mix and match:

>> x: [ [[1]] [[2]] [3 [4 5]] ]
== [[[1]] [[2]] [3 [4 5]]]

>> first pick x/3 2
== 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top