sort API design
Johannes Riecken
johannes.riecken at gmail.com
Thu Nov 21 22:19:45 UTC 2019
On Wednesday, 20 November 2019 at 09:33:25 UTC, Johannes Riecken
wrote:
> I had looked at how to do case-insensitive string sorting with
> Phobos and without looking at the documentation much, I went
> with the following code and then wrongly concluded that `<`
> does case-insensitive comparisons on strings by default:
>
> ```
> import std.algorithm;
> import std.stdio;
> import std.string;
>
> void main() {
> auto arr0 = ["foo", "bar", "Baz"];
> auto case_sensitive = sort!((a, b) => a < b
> )(arr0);
> auto case_insensitive = sort!((a, b) => a.toLower() <
> b.toLower())(arr0);
> writeln(case_sensitive);
> writeln(case_insensitive);
> }
> ```
> Output:
> ```
> ["bar", "Baz", "foo"]
> ["bar", "Baz", "foo"]
> ```
>
> Later I learned that I was trapped by `sort` being in-place but
> still returning a value. If this API were to be designed from
> scratch, I wonder if it would be possible to rule out this
> incorrect usage at compile-time while still retaining the other
> nice features of the `sort` function like being in-place and
> giving strong types which can be used to choose faster
> algorithms to further transform the result, etc.? Or are there
> any ideas in programming language research that would help with
> such a case?
Thanks, that's some nice ideas in this thread! I should
definitely get into the habit of using const wherever possible.
Jonathan, I think a major selling point of Phobos and D is that
in lots of cases it can catch erroneous API usage at compile time.
More information about the Digitalmars-d
mailing list