Safer casts

Dee Girl deegirl at noreply.com
Sat May 10 14:05:03 PDT 2008


Yigal Chripun Wrote:

> 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.

I agree! Strings and aliases are much less powerful than delegates and closures because they are static and can not have state.

But I am confused about something. I compiled this with phobos:

sort!(function bool(int a, int b) { return a > b; })(array);

There is clear difference in syntax from your examples. But my question is: what are the differences in semantics? Thank you, Dee Girl



More information about the Digitalmars-d mailing list