Search code examples
d

How does one peek and advnace a range inside a foreach loop


Inside a foreach loop which iterates over a range, I want to (1) advance and (2) peek over the next element in the range without advancing it.

import std.range: splitter;
import std.conv: parse;
foreach(numstr; line.splitter(',')) {
    const int code = parse!int(numstr);
    switch (code) {
        case 1:
                  auto next1 = // currentRange.next()
                  // calling next() advances the range
                  auto next2 = // currentRange.next()
                  auto next3 = // currentRange.next()
                  // ...
        case 2:
                  auto next1 = // currentRange.peek()
                  // calling peek() will not forward the range
                  currentRange.advanceBy(4);
                  // ...
        // ...
    }
}

Solution

  • (1) advance

    You could advance the range manually with popFront, but I would not recommend combining that with a foreach loop. Perhaps replace the foreach with while (!range.empty) ?

    (2) peek over the next element in the range without advancing it

    For this, advance a copy of it:

    • range.save.dropOne.front
    • range.save.drop(4).front

    Of course, the splitter will have to redo the work for each peek. To avoid this, save its result to an array, or use split.