Skip to content

Instantly share code, notes, and snippets.

@John-Colvin
Created September 4, 2017 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save John-Colvin/a732f46facbe43d158b5d8a291e23b09 to your computer and use it in GitHub Desktop.
Save John-Colvin/a732f46facbe43d158b5d8a291e23b09 to your computer and use it in GitHub Desktop.
/// map only on the specified index of each tuple element of the range `r`
auto mapOnPart(size_t i, alias f, R)(R r)
{
return r.map!(t => tuple(t[0 .. i].expand, f(t[i]), t[i + 1 .. $].expand));
}
/// map the whole tuple element to one part, copying the rest untouched
auto mapAllToPart(size_t i, alias f, R)(R r)
{
return r.map!(t => tuple(t[0 .. i].expand, f(t), t[i + 1 .. $].expand));
}
auto unzip(R)(R r)
if (isForwardRange!R
&& __traits(compiles, { enum size_t _ = ElementType!R.length; }))
{
import std.range : iota;
import std.algorithm : map;
import std.range : save;
import std.typecons : tuple;
import std.conv : to;
import std.string : join;
return mixin(`tuple(` ~
iota(ElementType!R.length)
.map!(i => `r.save.map!"a[` ~ i.to!string ~ `]"`)
.join(", ")
~ `)`
);
}
@("unzip")
unittest
{
import std.range : zip, ElementType;
import std.algorithm : equal;
auto a = [1, 2, 3, 4];
auto b = [5, 6, 7, 8];
auto p = zip(a, b).unzip();
assert(a.equal(p[0]));
assert(b.equal(p[1]));
}
auto unzipDynamic(R)(R r)
{
return r.front.walkLength.iota.map!(i => transversal(x, i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment