www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - chunkBy with inputRange buggy + proposal for mapCache to fix it

chunkBy can't backtrack on an inputrange (but ok with a forward range,
eg by uncommenting a .array below). This can be fixed using the
mapCache defined below. Is there another way without introducing
mapCache ?


$ echo 'abc' |  dmd -version=with_mapCache -run main.d

$ echo 'abc' |  dmd -version=with_map -run main.d
RT error: Attempting to popFront an empty map.

import std.algorithm:chunkBy,map,cache;
import std.range:walkLength;
import std.array:array;
import std.stdio;

template mapCache(alias fun){
  auto mapCache(T)(T a){
    struct B{
      T a;
      this(T a){ this.a=a; }
      void popFront(){ a.popFront; }
      auto front(){ return fun(a.front); }
      bool empty(){ return a.empty; }
    return B(a);

  alias mymap=map;
else version(with_mapCache)
  alias mymap=mapCache;

void test(){
  auto lines=stdin
    //.array // when uncommenting this, both works

  auto lines2=lines.array;
  // prints empty unless we uncomment above

void main(){
Jul 05