Safer casts
Yigal Chripun
yigal100 at gmail.com
Sat May 10 12:12:10 PDT 2008
Janice Caron wrote:
> On 10/05/2008, Dee Girl <deegirl at noreply.com> wrote:
>> Nice example! How did you do it? Did Tango change the compiler and added more methods to arrays? Thank you, Dee Girl
>
> Yeah, but look what you can do with Phobos.
>
> import std.algorithm;
>
> int[] array = [ 1, 2, 3, 4 ];
>
> // sort in descending order
> sort!("a > b")(array);
> assert(array == [ 4, 3, 2, 1 ]);
>
> // sort in ascending order
> sort(array);
> assert(array == [ 1, 2, 3, 4 ]);
>
> // sort with a delegate
> bool myComp(int x, int y) { return x > y; }
> sort!(myComp)(array);
> assert(array == [ 4, 3, 2, 1 ]);
>
> // Showcase stable sorting
> string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
> sort!("toupper(a) < toupper(b)", SwapStrategy.stable)(words);
> assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
here comes my personal emotional response: I hate the above code! it
smells to much like C++.
I really dislike the use of templates here, which is unnecessary, and
even more so the use of those strings. a Much better way would be to use:
sort(array, (int a, int b){ return x > y; });
I wish D would add the syntax sugar proposed by downs so that could be
written as:
sort(array, (int a, int b)) { return x > y; }
also, you can rewrite it as:
array.sort(...);
which is even better IMO.
-- Yigal
More information about the Digitalmars-d
mailing list