Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.range.inits and tails #9972

Open
dlangBugzillaToGithub opened this issue May 7, 2013 · 1 comment
Open

std.range.inits and tails #9972

dlangBugzillaToGithub opened this issue May 7, 2013 · 1 comment

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2013-05-07T17:38:31Z

Transfered from https://issues.dlang.org/show_bug.cgi?id=10042

CC List

Description

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 };
}
@dlangBugzillaToGithub
Copy link
Author

bearophile_hugs commented on 2013-10-16T15:58:15Z

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]

@LightBender LightBender removed the P4 label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants