[Issue 6004] std.range.unzip()

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sun May 7 05:49:38 PDT 2017


https://issues.dlang.org/show_bug.cgi?id=6004

Ulrich Küttler <kuettler at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |kuettler at gmail.com

--- Comment #4 from Ulrich Küttler <kuettler at gmail.com> ---
For forward ranges of tuples "unzip" can be implemented in a few lines. E.g.

import std.typecons, std.algorithm, std.range;

Tuple!(int,int) divMod(int n, int m) {
    return tuple(n / m, n % m);
}

auto unzip(Range)(Range r)
  if (isForwardRange!Range && isTuple!(ElementType!Range))
{
  import std.conv;

  auto generateElements(size_t length)
  {
    const s = iota(length)
              .map!(i => "r.map!(t => t[" ~ i.to!string ~ "])")
              .join(",");
    return "tuple(" ~ s ~ ")";
  }

  alias T = ElementType!Range;
  return mixin(generateElements(T.Types.length));
}

void main()
{
  import std.stdio, std.array;
  auto rs = iota(1, 20).map!(m => divMod(20,m)).unzip();
  writeln(rs[0].array);
  writeln(rs[1].array);
}

Not sure if this should go into phobos.

--


More information about the Digitalmars-d-bugs mailing list