给定以下代码
import std.datetime: Clock, SysTime, Duration;
SysTime[] times;
const n = 3;
foreach (i; 0..n) times ~= Clock.currTime;
是否有一个更简单的,也许是功能性的,更高阶的模式 哪个能达到同样的目的?
一个额外的好处是,如果可能的话,可能会通过一些就地构造模式来尽量减少元素的复制。
更新:
好的,这是我到目前为止的尝试:
enum arityMin0(alias fun) = __traits(compiles, fun());
auto apply(alias fun, N)(N n) if (isCallable!fun &&
arityMin0!fun &&
!is(ReturnType!fun == void) &&
isIntegral!N)
{
import std.range: iota, map;
return n.iota.map!(n => fun);
}
例如,被称为
import std.datetime: Clock;
auto times = 3.apply!(Clock.currTime).array;
还剩一个细节。限制条件
arity!fun == 0
在
中评估为false
auto times = 3.apply!(Clock.currTime).array;
因为这里的 arity 实际上是 0 和 1。
所以 arity!fun
在这种情况下计算为 1
因为 Clock.currTime
采用默认参数。
也许我们还需要 std.traits
中的 arityMin
和 arityMax
。
在那种情况下,我应该使用 __traits(compiles
来实现 arityMin
吗?
最佳答案
评估 currTime
三次:
auto times = 3.iota.map!(n => Clock.currTime).array();
计算 currTime
一次:
auto times = Clock.currTime.repeat(3).array();
关于范围构建模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954381/