I would like to join several sorted files into one big sorted file.
For that I came up with this snippet:
#!/usr/bin/env rdmd
import std.stdio;
import std.algorithm;
import std.typecons;
import std.array;
import std.range;
auto byMinimum(Ranges)(Ranges ranges)
{
auto getNonEmpty()
{
return ranges.filter!("!a.empty");
}
auto nonEmpty = getNonEmpty;
struct ByMinimum(Ranges)
{
bool empty()
{
return nonEmpty.empty;
}
auto front()
{
auto minRangeAndLine = nonEmpty.map!(range => tuple!("range",
"line")(range, range.front)).minElement!("a.line");
return minRangeAndLine;
}
void popFront()
{
auto minRangeAndLine = nonEmpty.map!(range => tuple!("range",
"line")(range, range.front)).minElement!("a.line");
minRangeAndLine.range.popFront;
nonEmpty = getNonEmpty;
}
}
return ByMinimum!(Ranges)();
}
void main(string[] files)
{
foreach (n; files[1 .. $].map!(name =>
File(name).byLine(No.keepTerminator)).array.byMinimum)
{
writeln(n.line);
}
}
I would like to get rid of the duplication that searches for the range
with the next minimum in terms of runtime but also in terms of code
written out. Unfortunately I have no idea how to even store the result
of this search in an attribute of ByMinimum, as I cannot writeout its type.
Kind regards,
Christian