July 05, 2017
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 ?


main.d:
```
/+
D20170705T174411

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

$ 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);
  }
}

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

void test(){
  auto lines=stdin
    .byLineCopy
    //.array // when uncommenting this, both works
    .chunkBy!(b=>b[0])
    .mymap!(a=>a[1].array)
  ;

  auto lines2=lines.array;
  // prints empty unless we uncomment above
  writeln(lines2);
}

void main(){
  test;
}
```