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

时间:2019-04-03 12:59:14

标签: d phobos

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

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

我尝试使用std.range : take,它“懒惰地只接受范围内的n个元素。”。它适用于数组,但不适用于范围(除非我将子范围放入数组中):

#!/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;
}

1 个答案:

答案 0 :(得分:1)

know your keys anyway做您想要做的事情:

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
}