2

In D you can do the following to create pair wise tuples of array elements:

auto a = [0, 1, 2, 3, 4];
auto x = a.zip(a.save.dropOne);

x can now be expanded to [[0, 1], [1, 2], [2, 3], [3, 4]].

I would like to generalize this concept to create n-tuples like this:

auto i = 0;
auto x = zip(generate!(() => a.save.dropExactly(i++)).take(n));

However, this leads to x being a range of Tuple!([1, 2, 3, 4]), Tuple!([2, 3, 4]) for n = 2.

This is plausible, since take produces subranges. But how can I create separate ranges to achieve the intended behavior?

Thanks in advance.

2
  • can you give an example of the 'intended behavior'? I don't understand the question.
    – rcorre
    Jul 24, 2017 at 12:01
  • For n=2 I would like to be able to expand x to [[0, 1], [1, 2], [2, 3], [3, 4]] using generate.
    – Jonas Wolf
    Jul 24, 2017 at 13:24

1 Answer 1

1

If I understand you correctly, you are looking for something like slide. It's already part of Phobos and will be included in the next release (2.076.0):

assert([0, 1, 2, 3].slide(2).equal!equal(
    [[0, 1], [1, 2], [2, 3]]
));
assert(5.iota.slide(3).equal!equal(
    [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
));

However, note that for random access ranges it's easy to achieve a sliding window iterator out of the box:

import std.range, std.stdio;
void main(string[] args)
{
    auto arr = 5.iota;
    auto n = 2;
    // Plain D arrays & slices
    foreach (i; 0 .. arr.length - n + 1)
        arr[i .. i + n].writeln;
    // [0, 1], [1, 2], [2, 3], [3, 4]

    // As a range
    arr = 10.iota;
    n = 3;
    int k = 0;
    generate!(() => arr[k .. k++ + n]).take(3).writeln;
    // [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

    n = 4, k = 0;
    generate!(() => arr[k .. k++ + n]).take(3).writeln;
    // [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
}

Play with this example online.

5
  • The generate is almost working: generate!(() => arr[k .. min(k++ + n, arr.length)]).take(3).writeln; also works if you take all possible subranges.
    – Jonas Wolf
    Jul 24, 2017 at 20:26
  • Well as mentioned - it depends on what you want to achieve.If you can clarify this, helping you will be easier ;-)
    – greenify
    Jul 24, 2017 at 20:41
  • You will get a range violation if the end of the slice is not limited.
    – Jonas Wolf
    Jul 25, 2017 at 3:49
  • What happened to slide in 2.076.0? Was it released? I cannot find it on dlang.org.
    – Jonas Wolf
    Sep 19, 2017 at 19:53
  • Unfortunately due to last minute complications its release has been delayed, but it's already in std/range.d (in case you want to copy/paste it to your project).
    – greenify
    Sep 21, 2017 at 5:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.