A lazy-chain for std.range?

Jakob Ovrum via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 26 20:37:26 PST 2016


On Saturday, 27 February 2016 at 04:31:03 UTC, Mint wrote:
> So, I noticed that one way I frequently use the chain function 
> defined std.range is as sort of an else-clause.
>
> ie.
>
>   return elements
>       .map!( . . . )
>       .filter!( . . . )
>       .chain(fallback.only)
>       .front;
>
>
> After transforming and filtering elements, chain would 
> effectively append a fallback element to the resulting range, 
> and then the first element would be taken. Hence if the result 
> of filter (or the initial range) was empty, the result would be 
> fallback.
>
> My concern is that in some cases my fallback is expensive to 
> compute, and acts as a performance sink.
>
> I'm wondering if about the possibility of having a similar 
> function that took a range as a lazy parameter. Specifically, a 
> the parameter would not be evaluated unless one of the 
> resulting range's functions were called. Thoughts?

With std.typecons.Option[1] it becomes:

     return elements
         .map!(…)
         .filter!(…)
         .frontOption
         .getOrElse(fallback);

`fallback` is a lazy argument.

[1] https://github.com/D-Programming-Language/phobos/pull/3915



More information about the Digitalmars-d mailing list