January 15, 2015 Re: commonLength | ||||
---|---|---|---|---|
| ||||
Posted in reply to Tobias Pankrath | On Thursday, 15 January 2015 at 19:30:21 UTC, Tobias Pankrath wrote:
> On Thursday, 15 January 2015 at 19:24:16 UTC, Nordlöw wrote:
>> On Thursday, 15 January 2015 at 13:13:57 UTC, Nordlöw wrote:
>>> I just discovered that zip has StoppingPolicy so why does
>>>
>>> auto commonPrefixLength(R...)(R ranges) if (ranges.length == 2)
>>> {
>>> import std.range: zip;
>>> return zip!((a, b) => a[0] != b[1])(ranges);
>>> }
>>
>> I did a silly mistake. The correct version is
>>
>> auto commonPrefixLength(S, T)(S a, T b)
>> {
>> import std.range: zip, StoppingPolicy;
>> import std.algorithm: countUntil, count;
>> const hit = zip(a, b).countUntil!(ab => ab[0] != ab[1]);
>> return hit == -1 ? zip(a, b).count : hit;
>> }
>>
>> This however needs to process zip(a, b) how do I avoid the extra count?
>>
>> If countUntil returned zip(a, b).count upon failure I would have been done...
>
> What's wrong with commonPrefix(..).length?
Only works if all input arguments have length property.
I would have implemented countUntil() to return
-length
upon failure instead of
-1
.
Then I could have just returned abs of the return value from commonUntil.
However
auto commonPrefixLengthAlt(S, T)(S a, T b) @safe pure @nogc nothrow
{
import std.algorithm: commonPrefix, count;
return commonPrefix(a, b).count;
}
works on dmd git master!
Limited to 2 arguments, though, but I'm find with that for now :)
|
January 15, 2015 Re: commonLength | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nordlöw | On Thursday, 15 January 2015 at 20:21:26 UTC, Nordlöw wrote:
> I would have implemented countUntil() to return
>
> -length
>
> upon failure instead of
>
> -1
> .
>
> Then I could have just returned abs of the return value from commonUntil.
I wonder if we could add an extra overload to countUntil in Phobos that takes an enum as first argument similar to zip's StoppingPolicy. Something like FailCountPolicy.
|
January 15, 2015 Re: commonLength | ||||
---|---|---|---|---|
| ||||
Posted in reply to Tobias Pankrath | On Thursday, 15 January 2015 at 19:30:21 UTC, Tobias Pankrath wrote:
> What's wrong with commonPrefix(..).length?
Ahh, sorry that works too. I'm surprised :)
DMD/Phobos has become really clever at avoiding allocation.
Seems there may be need for both
commonPrefixCount
and
commonPrefixLength
depending on whether string auto-decoding is needed or not.
|
Copyright © 1999-2021 by the D Language Foundation