[Issue 10042] New: std.range.inits and tails
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue May 7 17:38:33 PDT 2013
http://d.puremagic.com/issues/show_bug.cgi?id=10042
Summary: std.range.inits and tails
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: enhancement
Priority: P2
Component: Phobos
AssignedTo: nobody at puremagic.com
ReportedBy: bearophile_hugs at eml.cc
--- Comment #0 from bearophile_hugs at eml.cc 2013-05-07 17:38:31 PDT ---
I suggest to add to Phobos the inits() and tails() random-access ranges similar
to the Haskell functions:
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v:inits
This is a bare-bones forward-range implementation, with an usage example, a
inefficient function that finds the maximum subsequence:
import std.stdio, std.algorithm, std.range, std.typecons;
mixin template InitsTails(T) {
T[] data;
size_t pos;
@property bool empty() { return pos > data.length; }
void popFront() { pos++; }
}
struct Inits(T) {
mixin InitsTails!T;
@property T[] front() { return data[0 .. pos]; }
}
auto inits(T)(T[] seq) { return seq.Inits!T; }
struct Tails(T) {
mixin InitsTails!T;
@property T[] front() { return data[pos .. $]; }
}
auto tails(T)(T[] seq) { return seq.Tails!T; }
auto maxSubseq(T)(T[] seq) {
return seq
.tails
.map!inits
.join
.map!q{ tuple(reduce!q{a + b}(0, a), a) }
.reduce!max[1];
}
void main() {
[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1].maxSubseq.writeln;
[-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1].maxSubseq.writeln;
}
Using the key function for the max() function as proposed in Issue 4705 the
function becomes quite short:
auto maxSubseq(T)(T[] seq) {
return seq.tails.map!inits.join.reduce!(max!q{ a.sum });
}
Using maxs:
auto maxSubseq(T)(T[] seq) {
return seq.tails.map!inits.join.maxs!q{ a.sum };
}
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list