Forwarding arguments through a std.algorithm.map

Nordlöw per.nordlow at gmail.com
Fri Mar 16 19:52:48 UTC 2018


On Saturday, 10 March 2018 at 21:31:41 UTC, ag0aep6g wrote:
> auto forwardMap(alias fun, Ts ...)(Ts things)
> {
>     import std.meta: aliasSeqOf, staticMap;
>     import std.range: iota;
>     import std.typecons: Tuple;
>     alias NewType(size_t i) = typeof(fun(things[i]));
>     alias NewTypes = staticMap!(NewType,
>         aliasSeqOf!(iota(things.length)));
>     Tuple!NewTypes results;
>     static foreach (i, thing; things) results[i] = fun(thing);
>     return results;
> }

Found a slightly compacter way without `iota` and `aliasSeqOf` 
and with (deprecated) string-lambda support and single-pass 
initialization using `= void` and `emplace`:

/** Returns: `xs` forwarded through calls to `fun`.
  *
  * See also: 
https://forum.dlang.org/post/zjxmreegqkxgdzvihvyk@forum.dlang.org
  */
auto forwardMap(alias fun, Ts...)(Ts xs)
{
     import std.meta : staticMap;
     alias MappedTypeOf(T) = typeof(fun(T.init));
     alias NewTypes = staticMap!(MappedTypeOf, Ts);

     import std.typecons : Tuple;
     Tuple!NewTypes ys = void;
     import std.conv : emplace;

     import std.functional : unaryFun;
     alias fun_ = unaryFun!(fun);

     static foreach (immutable i, x; xs)
     {
         emplace(&ys[i], fun_(x));
     }
     return ys;
}

I believe this should go into Phobos somewhere. Into 
std.typecons, std.meta or std.algorithm?


More information about the Digitalmars-d-learn mailing list