Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays as separate type

Some scripting languages, such as Python and Javascript, have arrays (aka lists) as a separate datatype from hash tables (aka dictionaries, maps, objects). In other scripting languages, such as PHP and Lua, an array is merely a hash table whose keys happen to be integers. (The implementation may be optimized for that special case, as is done in the current version of Lua, but that's transparent to the language semantics.)

Which is the better approach?

  1. The unified approach is more elegant in the sense of having one thing rather than two, though the gain isn't quite as large as it might seem at first glance, since you still need to have the notion of iterating over the numeric keys specifically.

  2. The unified approach is arguably more flexible. You can start off with nested arrays, find you need to annotate them with other stuff, and just add the annotations, without having to rework the data structures to interleave the arrays with hash tables.

  3. In terms of efficiency, it seems to be pretty much a wash (provided the implementation optimizes for the special case, as Lua does).

What am I missing? Does the separate approach have any advantages?

like image 614
rwallace Avatar asked Jul 03 '11 18:07

rwallace


1 Answers

Having separate types means that you can make guarantees about performance, and you know that you will have "normal" semantics for things like array slicing. If you have a unified system, you need to work out what all operations, such as slicing, mean on sparse arrays.

like image 84
Marcin Avatar answered Oct 21 '22 03:10

Marcin