Issue 10042 - std.range.inits and tails
Summary: std.range.inits and tails
Status: REOPENED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-05-07 17:38 UTC by bearophile_hugs
Modified: 2024-12-01 16:17 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-05-07 17:38:31 UTC
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 };
}
Comment 1 bearophile_hugs 2013-10-16 15:58:15 UTC
Another usage example:

sequence!q{n}.inits.map!sum.take(20).writeln;

Should generate the the triangle number sequence (http://oeis.org/A000217 ), with an extra leading zero:

[0, 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171]
Comment 2 dlangBugzillaToGithub 2024-12-01 16:17:28 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9972

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB