Thread overview
lookahead on ranges
Apr 29, 2013
Sebastian Graf
Apr 29, 2013
bearophile
Apr 29, 2013
Sebastian Graf
April 29, 2013
Hi,

is there any way to to something like

    auto arr = [1,2,3,4,5];
    auto delta = arr.lookahead!"b-a"(1); // or probably pass 1 as template arg
    assert(equal(delta[], [1,1,1,1][]);

or like

    // lookahead returns range of tuples (template arg) or arrays (runtime arg)
    foreach (a, b; arr.lookahead!1)
        writeln(b-a);

on a range? I think I could possibly do this with zip, but I am curious if there is something more to the point to do it in phobos. In particular something that just buffers n eles and does not copy the input range to popFront() all of them.
April 29, 2013
Sebastian Graf:

> is there any way to to something like
>
>     auto arr = [1,2,3,4,5];
>     auto delta = arr.lookahead!"b-a"(1); // or probably pass 1 as template arg
>     assert(equal(delta[], [1,1,1,1][]);
>
> or like
>
>     // lookahead returns range of tuples (template arg) or arrays (runtime arg)
>     foreach (a, b; arr.lookahead!1)
>         writeln(b-a);

I think there isn't something like that in Phobos (I can't be fully sure because std.algorithm and std.range contain lot of powerful stuff, and it's not easy to know every possible combination of them).

So I think you should use zip.

Time ago I have suggested to add a second argument to chunks:
http://d.puremagic.com/issues/show_bug.cgi?id=6621

With that you can do something like:

auto arr = [1,2,3,4,5];
auto delta = arr.chunks(2, 1).map!(p => p[1] - p[0]);


Note that today this:

assert(equal(delta[], [1,1,1,1][]));

is written like this:

assert(equal(delta, [1,1,1,1]));

Or even:

assert(delta.equal([1,1,1,1]));

The online documentation is old.

Bye,
bearophile
April 29, 2013
On Monday, 29 April 2013 at 16:39:21 UTC, bearophile wrote:
>
> I think there isn't something like that in Phobos (I can't be fully sure because std.algorithm and std.range contain lot of powerful stuff, and it's not easy to know every possible combination of them).
>
> So I think you should use zip.
>
> Time ago I have suggested to add a second argument to chunks:
> http://d.puremagic.com/issues/show_bug.cgi?id=6621
>
> With that you can do something like:
>
> auto arr = [1,2,3,4,5];
> auto delta = arr.chunks(2, 1).map!(p => p[1] - p[0]);
>
>
> Note that today this:
>
> assert(equal(delta[], [1,1,1,1][]));
>
> is written like this:
>
> assert(equal(delta, [1,1,1,1]));
>
> Or even:
>
> assert(delta.equal([1,1,1,1]));
>
> The online documentation is old.
>
> Bye,
> bearophile

Thanks. Sounds good.