November 11, 2014 Re: cannot sort an array of char | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ivan Kazmenko | On 11/11/14 6:07 AM, Ivan Kazmenko wrote: > IK>> Why is "char []" so special that it can't be sorted? > > SS> Because sort works on ranges, and std.range has the view that > SS> char[] is a range of dchar without random access. Nevermind > SS> what the compiler thinks :) > SS> > SS> I believe you can get what you want with > SS> std.string.representation: > SS> > SS> import std.string; > SS> > SS> sort(c.representation); > > Thank you for showing a library way to do that. > I ended up with using a cast, like "sort (cast (ubyte []) c)". > And this looks like a safe way to do the same. It's safe but be careful. For instance, if c becomes an immutable(char)[] or const(char)[], then you will have undefined behavior. If you use the representation, it will properly reject this behavior. > Now, std.utf's byCodeUnit and std.string's representation seem like > duplicate functionality, albeit with different input and output types > (and bugs :) ). No, byCodeUnit is not an array, it's a range of char. They solve different problems, and mean different things. Note, byCodeUnit should work for sort, I'm surprised it doesn't. -Steve |
November 11, 2014 Re: cannot sort an array of char | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On Tuesday, 11 November 2014 at 13:20:53 UTC, Steven Schveighoffer wrote:
> On 11/11/14 6:07 AM, Ivan Kazmenko wrote:
>> IK>> Why is "char []" so special that it can't be sorted?
>>
>> SS> Because sort works on ranges, and std.range has the view that
>> SS> char[] is a range of dchar without random access. Nevermind
>> SS> what the compiler thinks :)
>> SS>
>> SS> I believe you can get what you want with
>> SS> std.string.representation:
>> SS>
>> SS> import std.string;
>> SS>
>> SS> sort(c.representation);
>>
>> Thank you for showing a library way to do that.
>> I ended up with using a cast, like "sort (cast (ubyte []) c)".
>> And this looks like a safe way to do the same.
>
> It's safe but be careful. For instance, if c becomes an immutable(char)[] or const(char)[], then you will have undefined behavior. If you use the representation, it will properly reject this behavior.
>
>> Now, std.utf's byCodeUnit and std.string's representation seem like
>> duplicate functionality, albeit with different input and output types
>> (and bugs :) ).
>
> No, byCodeUnit is not an array, it's a range of char. They solve different problems, and mean different things.
>
> Note, byCodeUnit should work for sort, I'm surprised it doesn't.
That's what he meant by "bugs" :-P
But it's been fixed already, thanks to H.S. Teoh.
|
Copyright © 1999-2021 by the D Language Foundation