commonLength
"Nordlöw" via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 15 12:21:25 PST 2015
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 :)
More information about the Digitalmars-d-learn
mailing list