Infinite range of nullable elements

Roland Hadinger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 17 00:42:07 PDT 2015


At this moment I'm tempted to implement a function taking a range 
of elements E and returning an infinite range of Nullable!E.

With this function ("cushion" for a lack of better name) I could 
do:

     auto a = [0,1,2,3,4,5,6,7,8,9];

     foreach (e ; a.cushion.take(20))
         writeln(e); // exactly 20 elements

This would allow chaining together algorithms that need to look 
ahead in a range.

Here's how I would implement the basic behaviour (could be 
extended to also forward bidirectional and random access 
functions):

---
     auto cushion(R)(R r)
         if (isInputRange!R)
     {
         static if (isInfinite!R) { return r; } else {

             struct _Cushion(R)
             {
                 R r;

                 alias E = ElementType!R;
                 alias NE = Nullable!E;

                 @property bool empty() { return false; }

                 @property NE front()
                 {
                     return !r.empty ? NE(r.front) : NE();
                 }

                 void popFront()
                 {
                     if (!r.empty) r.popFront();
                 }
             }

             return _Cushion!R(r);
         }
     }

---

I didn't find anything like this Phobos. Did I miss something? Is 
this a bad idea for some reason?



More information about the Digitalmars-d-learn mailing list