commonLength
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jan 15 11:49:14 PST 2015
On 01/15/2015 11:24 AM, "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...
The predicate version of count() seems to work for your case. If I
misunderstood, please explain with an added failing unit test:
auto commonPrefixLength(S, T)(S a, T b)
{
import std.range: zip;
import std.algorithm: count;
return zip(a, b).count!(ab => ab[0] == ab[1]);
}
unittest
{
assert(commonPrefixLength("açde", "") == 0);
assert(commonPrefixLength("açde", "xyz") == 0);
assert(commonPrefixLength("açd", "açde") == 3);
assert(commonPrefixLength("açdef", "açdef") == 5);
}
void main()
{}
Ali
More information about the Digitalmars-d-learn
mailing list