Search code examples
j

Convert boxed array to normal array?


Suppose I have a boxed array like;

┌─┬─┬─┐
│1│2│3│
└─┴─┴─┘

how do I covert it to a normal array such as 1 2 3?


Solution

  • Your example is not clear enough to specify exactly what is the wanted behavior on higher-dimension arrays. Thus there will be two solutions, which are the most commonly wanted behaviors in this kind of situations.

    The first solution is to use the builtin monadic verb raze ;, as such

      ]a=.<"(0) 1+i.3
    +-+-+-+
    |1|2|3|
    +-+-+-+
      ;a
    1 2 3
    

    Pretty straightforward. However, it should be noted that raze has rank _, and that it will always produce a list, that is, it will also flatten your array:

      ]a=.<"(0) 1+i.2 3
    +-+-+-+
    |1|2|3|
    +-+-+-+
    |4|5|6|
    +-+-+-+
      ;a
    1 2 3 4 5 6
    

    If you don't want that behavior, you can always use the rank conjunction ":

      ;"1 a
    1 2 3
    4 5 6
    

    Alternatively, you may also want to preserve the original shape of the array, in which case the monadic verb open > is probably what you want:

      ]a=.<"(0) 1+i.3
    +-+-+-+
    |1|2|3|
    +-+-+-+
      >a
    1 2 3
      ]a=.<"(0) 1+i.2 3
    +-+-+-+
    |1|2|3|
    +-+-+-+
    |4|5|6|
    +-+-+-+
      >a
    1 2 3
    4 5 6
    

    Finally, you should know that it's not necessary to create an array of unboxed values to operate on them, as creating this array may lead to unwanted behavior (especially with padding):

      ]a=.1 2;3 4 5
    +---+-----+
    |1 2|3 4 5|
    +---+-----+
      >a
    1 2 0
    3 4 5
    

    Suppose I'd want to add 1 to each atom inside the boxes of a. Opening a won't do, as that will create an additional element 0 that is required for padding, which won't be removed if I rebox the lists afterwards

      <"1>a
    +-----+-----+
    |1 2 0|3 4 5|
    +-----+-----+
      a -: <"1>a 
    0
    

    Instead, I can modify my verb "add 1" to work on boxes instead, with the conjunction under (dual) &.

      a=.1 2;3 4 5
      1&+&.>a
    +---+-----+
    |2 3|4 5 6|
    +---+-----+
    

    Note that there is no extra padding!