by slver · 5y ago · 0 comments
4 + 4
8
In array languages the same operator can be used for arrays; or equivalently you can say that the example above sums two arrays of length 1. In J, you can do this and expect it to work: 4 4 4 + 2 2 2
6 6 6
This is true for all the built-ins, and many user defined operations (as long as you don't fiddle with so called rank of the verb you're defining).Numpy is close to that, but there's still a distinction between arrays and scalars, while in array langauges that distinction is often blurred:
4 + 1 2 3
5 6 7
Edit: in J, you can have atoms, or scalars, but you need to box them: (3;4;5)
┌─┬─┬─┐
│3│4│5│
└─┴─┴─┘
but then you can't do anything with them until you unbox them again: (3;4;5) + 3
|domain error
| (3;4;5) +3
(+&4) each (3;4;5)
┌─┬─┬─┐
│7│8│9│
└─┴─┴─┘
(Examples straight from J REPL) [1, 2, 3].binaryMap([10, 10, 10], (a, b) => a * b) // Produces [10, 20, 30]
This would be easier to optimize when compiled because the expressions can be simplified and mapped to the right SIMD instructions.OTOH, your example is very verbose when compared to J's version:
1 2 3 * 10
10 20 30
Plus, in J it generalizes to higher dimensional arrays: i. 3 3
0 1 2
3 4 5
6 7 8
(1 + i. 3 3) * 10
10 20 30
40 50 60
70 80 90 [1, 2, 3].map(a => a * 10)
if I wanted to literally carry out that task alone. [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]].flatMap(a => a * 10)(>: i. 3 3) * 10
It's more about allowing the SIMD goodness without the ambiguity and restrictions of "scalar operators work on arrays" implemented naively.
There's a page on the various approaches to arrays in the APL family at https://aplwiki.com/wiki/Array_model .
Numbers (and character) are implemented as arrays with 0 dimensions. Text would be an array of characters with 1 dimension (the number of characters), and generally speaking the dimension of an array is a one dimensional list of non-negative integers. Many array languages also include an array type which is approximately the same as a C pointer to an array, with a bit of jargon thrown in to distinguish a reference to an array from the array itself.
Something like an SQL table in an array language would be implemented as a list of columns (rather than as a list of rows) and a corresponding list of column labels. This has some interesting benefits.
That said, functions in array language are typically not arrays (though they presumably would have a textual representation). So... not everything is an array.
nub=: (i.@# = i.~) # ]
5!:2 <'nub'
+-------------------+-+-+
|+--------+-+------+|#|]|
||+--+-+-+|=|+--+-+|| | |
|||i.|@|#|| ||i.|~||| | |
||+--+-+-+| |+--+-+|| | |
|+--------+-+------+| | |
+-------------------+-+-+
... so J functions have an array representation, at least.