Returning an empty range of a given type

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 13 23:41:44 PDT 2015


On 05/13/2015 07:47 PM, rcorre wrote:
> I've run into this situation a lot:
> I have a function that returns a range (in this case, a slice of a
> custom container).
> In some cases, the function needs to return an empty range.
>
> It sounded like takeNone was what I wanted:
>
> @nogc auto fun() {
>     return (some_condition) ? getRange() : getRange.takeNone;
> }
>
> but there is a return type ambiguity. I finally ended up doing this:
>
> @nogc auto fun() {
>     return (some_condition) ? getRange().take(size_t.max) :
> getRange.takeNone;
> }
>
> I'm not sure if this is clever or insane.
> It works, but just looks a bit crazy to me.
> Does anyone else run into this situation? Have any cool ways to solve it?
> MyRange is an inputRange, and I can't use a wrapper (InputRange) and
> keep the @nogc.

I needed the same thing in a code example of this chapter:

   http://ddili.org/ders/d.en/fibers.html

There is this function that returns a range:

auto byNode(const(Node) * node)
{
     return new FiberRange!(const(Node)*)(
         () => nextNode(node));
}

I am lucky because although the returned type is opaque to me, I know 
that it is constructed by a void lambda. So, I could pass (){} to the 
constructor to make an empty range:

auto byNode(const(Tree) tree)
{
     alias RangeType = typeof(byNode(tree.root));

     return (tree.root
             ? byNode(tree.root)
             : new RangeType(() {}));    // ← Empty range
}

Ali



More information about the Digitalmars-d-learn mailing list