2

Given the following code

import std.datetime: Clock, SysTime, Duration;
SysTime[] times;
const n = 3;
foreach (i; 0..n) times ~= Clock.currTime;

is there a simpler, perhaps functional, higher order pattern with which to achieve the same goal?

A bonus would to be, when possible, minimize copyings of the elements perhaps through some in-place construction pattern.

See also: http://forum.dlang.org/thread/[email protected]#post-yofbijaejfyftpcjdcvd:40forum.dlang.org

Update:

Ok here's my try so far:

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);
}

called as, for instance,

import std.datetime: Clock;
auto times = 3.apply!(Clock.currTime).array;

One detail left. The restriction

arity!fun == 0

evaluate to false in

auto times = 3.apply!(Clock.currTime).array;

because arity is actually either 0 and 1 here.

So arity!fun evaluates to 1 in this case because Clock.currTime takes a defaulted argument.

Maybe we need arityMin and arityMax in std.traits aswell.

In that case should I use __traits(compiles to implement arityMin?

1
  • Yes. It's better to test for capability rather than attributes. That way, your code will be more generic, and will work with e.g. functors. Feb 22, 2014 at 17:08

1 Answer 1

6

Evaluating currTime thrice:

auto times = 3.iota.map!(n => Clock.currTime).array();

Evaluating currTime once:

auto times = Clock.currTime.repeat(3).array();
1
  • Ok. Great. See follow up question above.
    – Nordlöw
    Feb 22, 2014 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.