Forwarding arguments through a std.algorithm.map

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Mar 16 20:39:33 UTC 2018


On 03/16/2018 03:52 PM, Nordlöw wrote:
> 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?

My knee-jerk reaction is that's a rather peculiar primitive to add to 
the standard library. -- Andrei


More information about the Digitalmars-d-learn mailing list