如何在 Dlang 中检查数组或范围长度是否至少为 N

how to check for array or range length being at least N in Dlang

对于 N=1,我会使用 std.array : empty 来检查长度是否至少为 N,并避免必须遍历整个输入。

对于N>1(或全N),D语言的惯用方式是什么?

我尝试使用 std.range : take 和 "Lazily takes only up to n elements of a range."。它适用于数组但不适用于范围(当然除非我将子范围放入数组中):

#!/usr/bin/env rdmd

module test_ranges;

void main()
{
    import std.container.dlist : DList;
    assert(lengthAtLeast([1, 2, 3], 2) == true);

    // assert(lengthAtLeast(DList!int(1, 2, 3)[], 2) == true);
    /*
test_ranges.d(64): Error: no property length for type Take!(Range)
test_ranges.d(10): Error: template instance `test_ranges.lengthAtLeast!(Range)` error instantiating
Failed: ["/usr/bin/dmd", "-v", "-o-", "test_ranges.d", "-I."]
    */
}

bool lengthAtLeast(R)(R input, size_t n)
{
    import std.range : take;

    return input.take(n).length == n;

    // this makes it work for arrays and ranges alike, but is not nice, is it?
    // import std.array : array;
    // return input.take(n).array.length == n;
}

walkLength 为所欲为:

bool lengthAtLeast(R)(R input, size_t n)
{
    import std.range.primitives : walkLength;
    return input.walkLength(n) >= n; // walks upTo n or returns the length if known
}