对于 N=1,我会std.array : empty
检查长度是否至少为 N,并避免遍历整个输入。
对于N>1(或全N),D语言的惯用方式是什么?
我尝试使用std.range : take
“Lazily 最多只占用一个范围内的 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;
}