Comment #0 by bearophile_hugs — 2011-02-05T17:22:30Z
A simple task asks to sort an array according to the length of its items. This is a D2 solution:
import std.stdio, std.algorithm;
void main() {
auto l = [['a','b','c'],['d','e'],['f','g','h'],['i','j','k','l'],['m','n'],['o']];
schwartzSort!((s){return s.length; })(l);
writeln(l);
}
It's supposed to print:
[['o'], ['d', 'e'], ['m', 'n'], ['a', 'b', 'c'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l']]
I suggest to add a simple len() function to std.algorithm, that allows to shorten that very common code (mapping lengths is a very common operation):
import std.stdio, std.algorithm;
size_t len(Range)(Range r) if (is(typeof(r.length))) {
return r.length;
}
void main() {
auto l = [['a','b','c'],['d','e'],['f','g','h'],['i','j','k','l'],['m','n'],['o']];
schwartzSort!len(l);
writeln(l);
}
In Python the "len()" function is a free function to allow it to be used as mapping function, sorting function for a Schwartz sort, etc. In Ruby there is a "size" standard attribute, and blocks are more used.
Comment #1 by peter.alexander.au — 2014-01-25T14:00:32Z
What's wrong with `walkLength`? If the range has `.length` (and isn't a narrow string) then walkLength just returns .length
Comment #2 by bearophile_hugs — 2014-01-25T15:10:22Z
(In reply to comment #1)
> What's wrong with `walkLength`?
Its semantics and performance are different for narrow strings, that are common use case. len is O(1), walkLength is sometimes O(n).
Comment #3 by peter.alexander.au — 2014-01-25T15:31:05Z
(In reply to comment #2)
> (In reply to comment #1)
> > What's wrong with `walkLength`?
>
> Its semantics and performance are different for narrow strings, that are common
> use case. len is O(1), walkLength is sometimes O(n).
So am I right in saying that your proposed 'len' function would return .length for narrow strings?
If that's the case then it would be a glaring inconsistency with the rest of Phobos, which has been very careful to treat strings as ranges of code points, and not code units. Having a single function break consistency for the sake of a few characters of typing convenience doesn't seem like a sensible thing to do.
Comment #4 by andrei — 2014-01-25T15:44:52Z
I understad the motivatio, but it's not nearly enough to justify a synonim for length.
Comment #5 by andrei — 2014-01-25T15:45:31Z
Sorry for the spelling errors - keyboard is acting up.