Skip to content

Instantly share code, notes, and snippets.

@0racle
Last active January 23, 2024 03:07
Show Gist options
  • Save 0racle/b34c8a5f809123b9b15d6665b0098f00 to your computer and use it in GitHub Desktop.
Save 0racle/b34c8a5f809123b9b15d6665b0098f00 to your computer and use it in GitHub Desktop.
A "partition" adverb in J (similar to APL's ⊆)

A "partition" adverb in J (similar to APL's ⊆)

P =: {{ (1, 2 </\ x) u;.1&((0 < x)&#) y }}

Partition on delimiter (à la (≠⊆⊢))

   ',' (~: <P ]) 'comma,separated,values'
┌─────┬─────────┬──────┐
│comma│separated│values│
└─────┴─────────┴──────┘

Partition on multiple delimiters (à la ((~∊⍨)⊆⊢))

   ',;' (-.@e.~ <P ]) 'commas,and;semicolons'
┌──────┬───┬──────────┐
│commas│and│semicolons│
└──────┴───┴──────────┘

Extract character groups (à la (∊⍨⊆⊢))

   nums =. '1234567890-'
   nums (e.~ <P ]) 'some 42 text -17 with 24 numbers'
┌──┬───┬──┐
│42-1724│
└──┴───┴──┘
   nums (e.~ ".P ]) 'some 42 text -17 with 24 numbers'
42 _17 24

Some examples from the Partition APL wiki article

    1 1 2 2 2 2 2 <P 'HiEarth'
┌──┬─────┐
│Hi│Earth│
└──┴─────┘
    1 1 2 2 2 0 0 <P 'HiEarth'
┌──┬───┐
│Hi│Ear│
└──┴───┘

Some examples from the Dyalog documentation

    1 1 1 2 2 3 3 3 <P 'NOWISTHE'
┌───┬──┬───┐
│NOW│IS│THE│
└───┴──┴───┘

    1 1 1 0 0 3 3 3 <P 'NOWISTHE'
┌───┬───┐
│NOW│THE│
└───┴───┘

   cmat =: ];._2 (0 : 0)
         Jan      Feb      Mar
Cakes    0        100      150
Biscuits 0        0        350
Buns     0        1000     500
)
   (+./ ' ' ~: cmat) <P"1 cmat
┌────────┬───┬────┬───┐
│        │Jan│Feb │Mar│
├────────┼───┼────┼───┤
│Cakes   │0100150│
├────────┼───┼────┼───┤
│Biscuits│00350│
├────────┼───┼────┼───┤
│Buns    │01000500│
└────────┴───┴────┴───┘

   ] n =. >: i. 4 4
 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16
   1 1 0 1 <P"1 n
┌─────┬──┐
│1 24 │
├─────┼──┤
│5 68 │
├─────┼──┤
│9 1012│
├─────┼──┤
│13 1416│
└─────┴──┘
   1 1 0 1 <P"1&.|: n
┌───┬───┬───┬───┐
│1 52 63 74 8│
├───┼───┼───┼───┤
│13141516 │
└───┴───┴───┴───┘
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment