A pass() identity range?

monarch_dodra monarchdodra at gmail.com
Sat Dec 22 01:48:29 PST 2012


On Saturday, 22 December 2012 at 08:55:35 UTC, bearophile wrote:
> I sometimes write code like:
>
> auto data = File("data.txt")
>             .byLine()
>             .map!(r => r.strip().dup)()
>             .filter!(r => !r.empty)()
>             .array();
>
>
> To help writing/improving/debugging such code maybe it's useful 
> to create a pass() range in Phobos. It's like a "identity 
> range" that just passes its inputs to its output, but also runs 
> a given lambda to the items that pass through it (the lambda 
> receives a const item, to avoid modifications of the data 
> passing through the chain):
>
>
> auto data = File("data.txt")
>             .byLine()
>             .pass(r => writeln("A: ", r))
>             .map!(r => r.strip().dup)()
>             .pass(r => writeln("B: ", r))
>             .filter!(r => !r.empty)()
>             .array();
>
>
> This usage of pass() allows to introduce debug prints inside 
> very long chains of such iterables, with no need to break them 
> apart and assign the parts to temporary variables just to see 
> what's going on in that chain.
>
> But it's not hard to do it with a not pure map:
>
>                 .map!((r){ writeln("B: ", r); return r; })()
>
> Or even with an evil comma operator:
>
>                 .map!(r => (writeln("B: ", r), r))()
>
> So I don't know how much useful that pass() is.
>
> Bye,
> bearophile

Bug reporting aside, it can be useful in the sense of *doing* 
something to each element, as opposed to "call a function and 
re-assign to original element".

This would be especially true for say: Mutating functions that 
return void, or just plain calling member functions.

I think it's a legit request. If anything, *map* could be 
re-implemented in terms of *call*.


More information about the Digitalmars-d-learn mailing list