9 ms·
Why perl has separate arrays and hashes: It's as if they thought it through
- antihero 15y agoHow is this different from Python's lists/dictionaries? Also IIRC PHP does internally differenciate between array(1,2,3) and array('blah'=>1, 'bloop' =>); Just the syntax is not as clear.
- pavel_lishin 15y agoWhat it does internally isn't much compensation for the fact that the code I write becomes harder to work with. :(
- masklinn 15y ago> How is this different from Python's lists/dictionaries? It's not. FWIW, I know of three languages which use the same data structure for arrays and associative arrays (/maps/hashes/whatever key/value collections are called these days): PHP, Lua and Awk (edit: had originally put "Tcl" here, but an other commenter set me straight: Tcl's arrays are called "list", Tcl's associative arrays are called "array", this got me confused. Sorry about that). Some functional languages also use lists of (key, value) pairs for small associative arrays (they may or may not provide "proper" associative arrays as well). They are called "association lists"[0] in many lisps (using a list of dotted pairs, rather than a list of lists) and "proplists"[1] in Erlang (using a mixed list of tuples and atoms). [0] http://www.gnu.org/s/emacs/manual/html_node/elisp/Association-Lists.html http://www.gnu.org/s/emacs/manual/html_node/elisp/Associatio... [1] http://www.erlang.org/doc/man/proplists.html http://www.erlang.org/doc/man/proplists.html
- beambot 15y agoFrom what I recall, Python (2.6) dictionaries do not necessarily preserve the order of items in the underlying structure. Eg. if "x = {1:1, 2:2, -1:5}", then x.items() will not necessaryily return "[(1, 1), (2, 2), (-1, 5)]" However, in Python 2.7+ ordered dictionaries in the collections library do preserve order. Perhaps this achieves the desired behavior?
- danudey 15y agoThe syntax is unclear, but also the behaviour is unclear. $var[] = "entry1"; $var['something'] = "entry2"; $var[] = "entry3"; $var[0] is now "entry1", and $var["something"] is "entry2", but what's the index for entry3? And if you iterate over the array, will you get entry2 before entry3? What if you create $var[$somestring], but $somestring is "29"? Now it will be at $var[29], and automatic indexing will reset to 30, which you may not expect. There's a lot of argument to "just don't write code like that", but with the inconsistencies in PHP library functions (and PHP's careless type conversion) it's easy to come across cases where this sort of "do something unexpected instead of throwing an error" behaviour can bite people in the ass down the road, through no fault of their own.
- antihero 15y agoOh yes, I don't deny that it's horribly done. I use my own classes "Dict" and "Li" instead of arrays whenever I need them to be specific, generally.
- sjs 15y agoDo so many languages conflate arrays and hashes? I know of PHP and JavaScript. PHP was not designed at all so no point discussing it. JavaScript was initially written in a week so we forgive Brendan Eich.
- deleted 15y ago[deleted]
- mikeryan 15y agoI'm not sure if I'd characterize Javascript's handling of arrays and hashes as conflated. The two are treated differently. To take an example from the post, Javascript Objects (hashes/Associative arrays) do not have a splice function. To answer your question I don't know of many languages which conflate the two. I know a lot of languages which offer similar methods, to create parity between arrays and hashes (since they are similar enough data structures) but not many which treat them the same.
- __david__ 15y ago> I'm not sure if I'd characterize Javascript's handling of arrays and hashes as conflated. Insomuch as [] and {} produce arrays and object, yes, you are correct. But those objects are strikingly similar and the functions in each prototype work on the other. To the outside observer, only the length bit works differently. I can do: a = new Array(); a["b"] = 1; for (x in a) { /* x will be "b" here*/ } a.length /* 0 */ and d = {0:"a",1:"b",2:"c",3:"d",length:4} Array.prototype.slice.call(d, 1,3) /* returns ["b", "c"] */ That's conflated a little bit.
- m0th87 15y agoJavaScript does not do this. It doesn't even have hashes in the traditional sense (all keys are stringified in prototypical objects).
- kylemaxwell 15y agoThat's a good question, because hashes (especially the deliciously-named "multi-dimensional associative arrays") figure so prominently in most of the stuff I do. I'd like to think Python or maybe Ruby does this well.
- pkulak 15y agoUsing the same object for arrays and hashes seems like a terrible idea long before thinking about it this much. JavaScript does it, but JS goes for this super-simple, everything-is-a-function-hash-thing simplicity
- mikeryan 15y agoAs stated above Javascript does not do this it has separate array and Object types. Javascript developers might.
- voyou 15y agoNo it doesn't. Arrays are a type of Object, they're not distinct.
- masklinn 15y ago> JavaScript does it No, javascript does not.
- pkulak 15y agozoidberg:~ phil$ node > a = {} {} > a[1] = 56 56 > a['1'] 56 > a = [null, 56] [ null, 56 ] > a['1'] 56 > a[1] 56 > typeof a 'object'
- ianterrell 15y agoThat this post has so many upvotes is evidence that a lot of nonprogrammers read HN.
- gaius 15y agoQuite. The whole point (haha) of an array is that you take a pointer to its first item + (the size of each item * the index number) and get a pointer to the item you want, which is bloody quick. No hashtable can compete with that - a hash is a compromise for when you can't use an int for whatever reason.
- neuroelectronic 15y agoThat's not the whole point of an array, an array also has practical uses!
- andrewflnr 15y agoI don't understand this comment. I'm a programmer, designing a language in my spare time, and I found it interesting, since I considered going the Lua/PHP route with my collections. I thought it was nice to find an article about actual programming an HN again, and I don't know why non-programmers would upvote it. Please explain. I'm really curious.
- ianterrell 15y agoMy comment was reflecting my intuition that most programmers would not find the blog post useful or insightful. The first two sentences of the blog post are, "I wonder why we have separate arrays and hashes in Perl. Other languages don't do it." However, as evidenced by only 4 contrary languages listed in the comments here, the vast majority of programming languages have separate array and hash structures. Much of the post is absolutely trivial. The post is a combination of circular reasoning (arrays and hashes must be different because they... are different) and some sort of straw man gedanken (well it would be easy to do if we did this but then that doesn't work, so obviously this way's "thought out"). It's a whole post to point out that arrays and hashes are different and are used differently. Hurray? Let's upvote it?
- wvenable 15y agoThe PHP array is a wonderful data structure with an awesome set of properties. This blog post contains a lot of "problems" that are somewhat trivial and have been reasonably solved in PHP. This comment will be downvoted to oblivion without discussion.
- MostAwesomeDude 15y agoYou made my morning, good sir. I could not stop laughing. You have brought mirth and cheer to our workplace.
- pavel_lishin 15y ago> This comment will be downvoted to oblivion without discussion. If you can see the future, I recommend playing the lottery. If you're a snarky ass, I recommend not commenting. I've been working with PHP for five+ years now, and only started working with Python in the last year or so. You're right - working with PHP's arrayhash isn't too terribly complicated, but having actual arrays and hashes as different types is super convenient. At least once a day, I think fondly of Python and wish I could use it - list comprehensions and negative indices could eliminate the need for half of PHP's array functions and make for cleaner and more readable code.
- wvenable 15y ago> If you can see the future, I recommend playing the lottery. I can't see the future, but I can edit the past. It's just a little disappointing to be downvoted without anyone actually commenting on the subject. > but having actual arrays and hashes as different types is super convenient. I agree especially if, in the language, arrays and hashes are objects with methods. I didn't claim PHP's arrays were the greatest data structure on earth but ordered hashes that special-cases integer indexes is a pretty nice procedural-style data structure. PHP doesn't really have arrays; it's just the hash type is flexible enough to do double-duty. Apparently, on Hacker News, having such opinions is both downvote worthy and punch-in-the-face worthy.
- pavel_lishin 15y ago
- haberman 15y agoArguing that this cannot reasonably be done is unconvincing when well-designed languages like Lua pull it off. The only thing about Lua's tables that consistently confuses people is the behavior of the length operator in the presence of "holes." The previous, somewhat confusing definition in Lua 5.1 (http://www.lua.org/manual/5.1/manual.html#2.5.5 http://www.lua.org/manual/5.1/manual.html#2.5.5) has been replaced with: The length of a table t is only defined if the table is a sequence, that is, all its numeric keys comprise the set {1..n} for some integer n. In that case, n is its length. Note that a table like {10, 20, nil, 40} is not a sequence, because it has the key 4 but does not have the key 3. (So, there is no n such that the set {1..n} is equal to the set of numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence. A program can modify the behavior of the length operator for any value but strings through the __len metamethod. (http://www.lua.org/work/doc/manual.html#3.4.6 http://www.lua.org/work/doc/manual.html#3.4.6)
- kevinpet 15y agoSo Lua is able to pull it off, but there's something that consistently confuses people? Forgive me, but hose sound contradictory.
- alexbell 15y agoIt's almost as if the majority of programming languaguages are "thought through". I mean, really, who designs a programming language and doesn't think it through? It's a nontrivial undertaking typically undertaken by people that are smarter than the average bear.
- wunderfool 15y ago> who designs a programming language and doesn't think it through? "I'm not a real programmer. I throw together things until it works then I move on." Rasmus Lerdorf (src:http://en.wikiquote.org/wiki/Rasmus_Lerdorf http://en.wikiquote.org/wiki/Rasmus_Lerdorf)
- birken 15y agoFirst, it is pretty funny for this poster to use this as a reason why perl is a well thought out language. It like all languages has pros and cons, and picking one thing about perl that isn't even unique to perl isn't a good example of how perl is so well thought out. Second, I agree with the premise that having two separate structures is better, but a lot of the issues brought up in this post just don't come up in the real world. For example with PHP once you understand that the array() construct is just a hash map with a linked list that stores the ordering, a lot of the these complications are much less complicated. Just don't think of the keys as indexes in an array, think of them as keys in a hash map that have nothing to do with ordering. If you want to change the order, you need to change the linked list, which initially is set by insert order but can be changed to something else by using various sort functions. Again, I'm not saying this is the greatest design in the world, but I am saying that living with this design in practical application isn't a big deal. In fact, the biggest annoyance has nothing to do with any coding stuff, it is just that you pay a huge memory penalty if you just want a simple array of items. Luckily PHP added a few newer data structures (http://www.php.net/manual/en/spl.datastructures.php http://www.php.net/manual/en/spl.datastructures.php) like SplFixedArray which are much more memory efficient. Obviously in standard usage the memory doesn't really matter, but in some cases where you want very large data structures these new objects come in handy.
- SwellJoe 15y agoIt like all languages has pros and cons, and picking one thing about perl that isn't even unique to perl isn't a good example of how perl is so well thought out. I believe you've misread the intent of the title. I read it as an answer to the question: "Why does Perl have arrays and hashes, even though the language I'm used to does not?" And, this article takes a decent stab at explaining why Perl has arrays and hashes. It does not, as far as I can tell, make any attempt to explain why this proves that Perl is superior to all other languages or is more thought-out than other languages (except perhaps those languages that don't have separate array and hash datatypes). The way I read it, it's saying in a lot more words, "You'll like it once you get used to it."
- skimbrel 15y agoThis was a fun post, but I found the other post on this blog more interesting: http://altreus.blogspot.com/2011/06/anatomy-of-types.html http://altreus.blogspot.com/2011/06/anatomy-of-types.html Not terribly useful to anyone who's been around the block in Perl at least once, but it's a great explanation of the three Perl variable types. Saving it for the next time I need to teach someone Perl.
- deleted 15y ago[deleted]
- Goladus 15y agoArray and hash types in perl likely evolved bottom-up from the lower-level data structures of the same name. Other languages use terms like "List" and "Associative Array" for their abstract data types to differentiate from the implementation techniques. And yes, lists and associative arrays have slightly different properties, as do sets, stacks, and queues.
- drdaeman 15y agotl;dr: arrays, dictionaries, ordered dictionaries (lists, sets and so on) are all different classes of data structures with different properties. To be efficient one should chose best one, not rely on some "all included" generic datatype.