3 ms·
If I may try to briefly explain/defend the naming as well as expand on the need for it... In Perl 5, 'reverse' did all of the three things: it reversed strings
by masak 17y ago
If I may try to briefly explain/defend the naming as well as expand on the need for it...
In Perl 5, 'reverse' did all of the three things: it reversed strings (in scalar context), or lists/hashes (in list context). The latter two weren't really distinguished, since a hash in Perl 5 is just an (even-element) list that you assign to a hash variable.
In Perl 6, 'wantarray' http://perldoc.perl.org/functions/wantarray.html http://perldoc.perl.org/functions/wantarray.html is gone, and not even built-in methods rely on figuring out the void/scalar/list context of the caller. Which means that we don't do the trick described in the blog post to make 'reverse' do either string or list reversal.
Very well, no problem. What we lack in 'wantarray' we make up with a type system. We just stick the string-reversing 'reverse' method on the type Str, and the list-reversing one on the type List. All good and well. (In fact, we put the string-reversing one on Any, and let it coerce to Str when needed.)
But wait. There are some corner cases where this causes problems. Sometimes a scalar variable contains a list of things, and sometimes a list contains but one element. In either case, we try to magically guess between the two uses, and get it wrong. So maybe making those two behaviours homonyms wasn't too good an idea after all.
Hence the need for distinguishing 'flip' and 'reverse'. By distinguishing 'invert', we can make it a bit smarter in case of hash key collisions. The 'magical guessing' dilemma goes away, because it's clear you mean a list when you say 'reverse' and a string when you say 'flip'.
The names are fairly well-chosen, considering what they do. You flip a single thing (string), reverse the order of a sequence of elements (list), and invert a mathematical mapping (hash).
- RyanMcGreal 17y agoThanks for the explanation. I guess I'm in the habit of thinking of a string as a list of characters. :)
- masak 17y agoHah, then I grok your initial reaction better. :) There is actually a class in Perl 6, called Buf, for when you want to talk about a sequence of bytes rather than a sequence of characters/graphemes. Buf is array-indexable; in fact it works a little like a string a little like an array. It's there to make it harder to screw encodings up. See http://use.perl.org/~masak/journal/39236 http://use.perl.org/~masak/journal/39236 for how.