www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - problem with the variadic template

reply baleog <maccarka yahoo.com> writes:
Hello
I want to write "map" function with the Common Lisp "mapcar" behaviour. But i
don't understand how to write one template for the N-argument delegate. 
This is how it works now:

T[] map(T, T1)(T delegate(T1) fun, T1[] xs) {
  T[] result; result.length = xs.length;
  foreach (i,x; xs)
    {
      result[i] = fun(x);
    }
  return result;
}
T[] map(T,T1,T2)(T delegate(T1, T2) fun, T1[] xs, T2[] ys) {
  T[] result; result.length = reduce!(min)(xs.length,[ys.length]);
  for (int i = 0; i<result.length; ++i)
    {
      result[i] = fun(xs[i], ys[i]);
    }
  return result;
}

How can i improve the code?

Thank you
Jul 05 2008
parent "Koroskin Denis" <2korden gmail.com> writes:
On Sun, 06 Jul 2008 02:19:09 +0400, baleog <maccarka yahoo.com> wrote:

 Hello
 I want to write "map" function with the Common Lisp "mapcar" behaviour=

 But i don't understand how to write one template for the N-argument  =

 delegate.
 This is how it works now:

 T[] map(T, T1)(T delegate(T1) fun, T1[] xs) {
   T[] result; result.length =3D xs.length;
   foreach (i,x; xs)
     {
       result[i] =3D fun(x);
     }
   return result;
 }
 T[] map(T,T1,T2)(T delegate(T1, T2) fun, T1[] xs, T2[] ys) {
   T[] result; result.length =3D reduce!(min)(xs.length,[ys.length]);
   for (int i =3D 0; i<result.length; ++i)
     {
       result[i] =3D fun(xs[i], ys[i]);
     }
   return result;
 }

 How can i improve the code?

 Thank you

There already exists a map function in D2, see std.algorithm = (http://www.digitalmars.com/d/2.0/phobos/std_algorithm.html), take a loo= p = at it.
Jul 05 2008