3 ms·
It’s the curse of the optional arguments. Same thing with parsing numbers where the second argument magically specifies the base. If the comparison function ar
by alkonaut 7y ago
It’s the curse of the optional arguments. Same thing with parsing numbers where the second argument magically specifies the base.
If the comparison function argument was mandatory in sort() this wouldn’t be a problem.
- masklinn 7y ago> It’s the curse of the optional arguments. Same thing with parsing numbers where the second argument magically specifies the base. Stupid defaults is not "the curse of optional arguments", it's the curse of stupid defaults. Most languages have defaults for these two operations yet have proper defaults rather than stupid ones. Python's list.sort() and int() certainly do, so do Java's Collections.sort() and Integer.parseInt(). Uniquely awful defaults is a historical (and defining) feature of javascript, not of having default values, or optional arguments.
- alkonaut 7y agoThe horror that arises in js is due to a combination of unfortunate things like function arity, and coercion. The one I was thinking of is the famous [1,2,10].map(parseInt) It’s several things that on their own aren’t mad which taken together produces a crazy result. 10 as the default for an optional second argument of parseInt is fine. But map should only use a single argument closure by default. So map(parseInt) must be equivalent to map(x -> parseInt(x)).
- Legogris 7y agoA different comparison function would not make efficient QuickSort stable.
- alkonaut 7y agoIt’s not the stability that bothers me but the fact that the comparison function is implicit and basically is (a, b) -> a.toString().compareTo(b.toString()) Unlike say int.parse() where 10 is a reasonable default for radix, doing string comparison as default is almost never what the caller wants, so is a bad default. Functions where there is no obvious (99% of the time the desired value) should not have a default value when the argument is omitted. I’d much rather have things.sort() just fail and force me to specify the comparison, than to see it sort alphabetically. As a side note: a second optional argument specifying stability true/false would be reasonable. True could be the default too, since unstable sorting is effectively an optimization with a tradeoff.