How to repeat a function call?

Simen Kjærås simen.kjaras at gmail.com
Wed Apr 2 12:01:53 PDT 2014


I'm trying to create a function that repeats a function call N times. 
The exact use case is generating an N-dimensional tuple:

import std.typetuple;
import std.typecons;

template Repeat(size_t n, T...) {
     static if (n == 1) {
         alias Repeat = T;
     } else static if (n) {
         alias Repeat = TypeTuple!(Repeat!(n /2, T), Repeat!((n +1)/2, T));
     } else {
         alias Repeat = TypeTuple!();
     }
}

auto fun1(size_t dim, T)(lazy T fn) {
     return tuple(Repeat!(dim, fn));
}

auto fun2(size_t dim, alias fn)() {
     return tuple(Repeat!(dim, fn));
}

void main() {
     int a = 0;
     assert(fun1!3(a++) == tuple(0,1,2));
//    assert(fun2!(3, ()=>a++) == tuple(0,1,2));
}

Now, the call to fun1 works great. But I'd like to specify fn at 
compile-time, thus doing something more like fun2. fun2 of course, does 
not work (else why would I ask?).

I tried staticMap'ing a template that calls its parameter over the 
result of Repeat in Fun2, but that did not work:

template call(alias fn) {
     alias call = TypeTuple!(fn());
}

auto fun3(size_t dim, alias fn)() {
     return tuple(staticMap!(call, Repeat!(dim, fn)));
}

fun3 ends up trying to evaluate the function call at compile-time, and 
fails because a++ can't be executed until run-time.

Better ideas, please?

--
   Simen


More information about the Digitalmars-d-learn mailing list