Indexing with nested vectors in APL

Viewed 139

I have a vector of vectors that contain some indices, and a character vector which I want to use them on.

A←(1 2 3)(3 2 1)
B←'ABC'

I have tried:

      B[A]
RANK ERROR
      B[A]
       ∧
      A⌷B
LENGTH ERROR
      A⌷B
       ∧

and

      A⌷B
LENGTH ERROR
      A⌷¨B
       ∧

I would like

┌→────────────┐
│ ┌→──┐ ┌→──┐ │
│ │ABC│ │CBA│ │
│ └───┘ └───┘ │
└∊────────────┘

to be returned, but if i need to find another way, let me know.

3 Answers

The index function is a bit odd. To select multiple major cells from an array, you need to enclose the array of indices:

      (⊂3 2 1)⌷'ABC'
CBA

In order to use each of two vectors of indices, the array you're selecting from needs to be distributed among the two. You can use APL's scalar extension for this, but then the array you're selecting from needs to be packaged as a scalar:

      (⊂1 2 3)(⊂3 2 1)⌷¨⊂'ABC'
┌→────────────┐
│ ┌→──┐ ┌→──┐ │
│ │ABC│ │CBA│ │
│ └───┘ └───┘ │
└∊────────────┘

So to use your variables:

      A←(1 2 3)(3 2 1)
      B←'ABC'
      (⊂¨A)⌷¨⊂B
┌→────────────┐
│ ┌→──┐ ┌→──┐ │
│ │ABC│ │CBA│ │
│ └───┘ └───┘ │
└∊────────────┘

Note that, if you are generating permutations which all have the same length, you may be better off avoiding nested arrays. Nested arrays force the system to follow pointers, while simple arrays allow sequential access to densely packed data. This only really matters when you have a LOT of data, of course:

      ⎕←SIMPLE←↑A ⍝ A 2×3 matrix of indices
1 2 3
3 2 1
      (⊂SIMPLE)⌷B
ABC
CBA
      B[SIMPLE] ⍝ IMHO bracket indexing is nicer for this
ABC
CBA
      ↓B[SIMPLE] ⍝ Split if you must
┌───┬───┐
│ABC│CBA│
└───┴───┘

In NARS2000, easy:

  A←(1 3 2)(3 2 1)
  B←'ABC'
  ⎕fmt {B[⍵]}¨¨A
┌2────────────┐
│┌3───┐ ┌3───┐│
││ ACB│ │ CBA││
│└────┘ └────┘2
└∊────────────┘
  C←(1 3 2 3 2 1)(3 2 1) 
  ⎕fmt {B[⍵]}¨¨C
┌2───────────────┐
│┌6──────┐ ┌3───┐│
││ ACBCBA│ │ CBA││
│└───────┘ └────┘2
└∊───────────────┘
Related