Tally ≢
#
Monadic primitive function ≢
is “Tally” — the length of the leading axis of its argument array:
⊢A3 ← 2 3 4⍴⍳24 ⍝ rank-3 array
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
⍴A3 ⍝ ⍴ returns _vector_ shape
2 3 4
≢A3 ⍝ ≢ returns _scalar_ tally
2
Now we can code an “average” function for arrays of any rank:
avg ← {(+⌿⍵)÷≢⍵} ⍝ leading-axis average
avg 1 2 3 4 ⍝ average of vector
2.5
avg A3 ⍝ average along leading axis
7 8 9 10
11 12 13 14
15 16 17 18
avg 42 ⍝ average of scalar
42
Rank ⍤
#
Dyadic primitive operator ⍤
is “Rank” - operand function applied to/between subarrays of given rank:
100 200 (+⍤0 2) A3 ⍝ scalars (0) plus matrices (2)
101 102 103 104
105 106 107 108
109 110 111 112
213 214 215 216
217 218 219 220
221 222 223 224
A3 ⍝ rank-3 array
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
avg A3 ⍝ average of rank-3 array
7 8 9 10
11 12 13 14
15 16 17 18
(avg⍤2)A3 ⍝ average of matrix sub-arrays
5 6 7 8
17 18 19 20
(avg⍤1)A3 ⍝ average of vector sub-arrays
2.5 6.5 10.5
14.5 18.5 22.5
(avg⍤0)A3 ⍝ average of each scalar item
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
(avg A3) ≡ (avg⍤3)A3 ⍝ average of rank-3 array
1
(avg⍤¯1)A3 ⍝ for rank-3 argument, same as ⍤2
5 6 7 8
17 18 19 20
Key ⌸
#
Monadic primitive operator ⌸
is “Key” - right argument items grouped according to left argument key values:
'FMF' {⍺ ⍵}⌸ ↑'Jane' 'Jean' 'Joan' ⍝ group by gender
┌─┬────┐
│F│Jane│
│ │Joan│
├─┼────┤
│M│Jean│
└─┴────┘
(↑'Red' 'Blue' 'Red') {⍺ ⍵}⌸ 10 20 30 ⍝ group by colour
┌────┬─────┐
│Red │10 30│
├────┼─────┤
│Blue│20 │
└────┴─────┘
The monadic case uses ⍵
as keys and (⍳≢⍵)
as values to be grouped:
{⍺ (≢⍵) ⍵}⌸ 'Mississippi' ⍝ letter count
┌─┬─┬────────┐
│M│1│1 │
├─┼─┼────────┤
│i│4│2 5 8 11│
├─┼─┼────────┤
│s│4│3 4 6 7 │
├─┼─┼────────┤
│p│2│9 10 │
└─┴─┴────────┘
{≢⍵}⌸ ?1000⍴6 ⍝ distribution of 1000 dice
164 171 187 150 160 168
⊢A2 ← ↑ 5⍴'Red' 'Blue' 'Green' ⍝ rank-2 array
Red
Blue
Green
Red
Blue
{⍺ ⍵}⌸ A2 ⍝ group by colour
┌─────┬───┐
│Red │1 4│
├─────┼───┤
│Blue │2 5│
├─────┼───┤
│Green│3 │
└─────┴───┘
Extension of ⍳
#
Dyadic primitive function ⍳
is extended for left arguments of rank greater than 1:
A2 ⍳ 'Blue ' ⍝ row index
2
A2 ⍳ ↑'Green' 'Grass' ⍝ row indices
3 6
Forks#
New syntax: A sequence of three functions in isolation is a “fork”.
mean ← +⌿ ÷ ≢ ⍝ (f g h)⍵ → (f ⍵) g (h ⍵)
mean ⍝ tree-style display of fork
┌─┼─┐
⌿ ÷ ≢
┌─┘
+
mean 1 2 3 4 ⍝ mean item of vector
2.5
A dyadic fork:
12 (-,÷) 3 ⍝ ⍺(f g h)⍵ → (⍺ f ⍵) g (⍺ h ⍵)
9 4
Longer “function trains” are grouped in threes from the right
6 (+,-,×,÷) 3 ⍝ (... f g h j k) → (... f g(h j k))
9 3 18 2
Atops#
Two function in isolation are an “Atop”:
'Banana' (~∊) 'an' ⍝ ⍺(f g)⍵ → f (⍺ g ⍵)
1 0 0 0 0 0
2 2 2 (⍉⊤) ⍳3 ⍝ transpose of encode
0 0 1
0 1 0
0 1 1
Monadic Atop is just composition:
rank ← ⍴⍴
rank A3
3