www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - A lazy-chain for std.range?

reply Mint <mintie wute.com> writes:
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?
Feb 26 2016
parent reply Jakob Ovrum <jakobovrum gmail.com> writes:
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
Feb 26 2016
parent Mint <mintie wute.com> writes:
On Saturday, 27 February 2016 at 04:37:26 UTC, Jakob Ovrum wrote:
 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
Cool. I'll have to look this over. Mostly because having a function that takes a lazy range is also important for some of the stuff I'm doing. My only concern is how fragmented the std lib is becoming. Range related functions in std.algo, std.array, std.range, and now std.typecons (which std.variant is separate from, for whatever reason). Regardless, that's a different discussion in and of itself.
Feb 26 2016