Adjacent Pairs Range

Bahman Movaqar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 12 04:34:02 PDT 2015


On 09/12/2015 03:09 PM, "Nordlöw" wrote:
> InputRange please, not RandomAccessRanges ;)

Oops!  Here's one using only `InputRange` interface:

    T[][] collate(T)(T[] a)
    {
      alias CollateResult = Tuple!(T[][], "result", T, "tlHd");
      CollateResult _collate(CollateResult collres)
      {
        if (!a.empty) {
          auto newTlHd = a.front;
          a.popFront();
          return _collate(
            CollateResult(
              collres.result ~ [collres.tlHd, newTlHd],
              newTlHd
            )
          );
        } else {
          return collres;
        }
      }

      if (!a.empty) {
        auto tlHd = a.front;
        a.popFront();
        return _collate(
          CollateResult([], tlHd)
        ).result;
      } else {
        return [];
      }
    }

    unittest {
      writeln([10, 20, 30].collate!int);
    }


-- 
Bahman Movaqar


More information about the Digitalmars-d-learn mailing list