Nifty chaining

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 4 08:45:43 PDT 2010


On Mon, 04 Oct 2010 11:28:53 -0400, Peter Alexander  
<peter.alexander.au at gmail.com> wrote:

> == Quote from Steven Schveighoffer (schveiguy at yahoo.com)'s article
>> I personally find this much more pleasant:
>> auto numAdded = lengthChain(a).add(1,2,3).add(b).add(c
> [1..3]).delta;
>> than:
>> int numAdded = void;
>> with(a)
>> {
>>    auto olength = length;
>>    add(1,2,3);
>>    add(b);
>>    add(c[1..3]);
>>    numAdded = length - olength;
>> }
>
> But if add just returns the delta rather than the reference then
> it's just:
>
> with (a) numAdded = add(1,2,3) + add(b) + add(c[1..3]);
> // (I'm hoping 'with' works like this! Can't test here)

I think it does work, and is much better than my example of with.  There's  
still the issue of declaring numAdded before the with statement.  I think  
because with is a statement, you can't really use it as an expression.

Thanks for your example, I definitely had not thought of using with  
multiple times within an expression, it's a good idea.

>
> or
>
> numAdded = a.add(chain([1,2,3], b, c[1..3]);
>
> (I'm assuming b was a range here, otherwise you could just add it
> to the end of the first expression).

It's not, it's another collection (an Iterator!V interface).

Here is another example from dcollections:

     Deque concat(List!(V) rhs)
     {
         return dup().add(rhs);
     }

I believe without chaining, this would be:

auto retval = dup();
dup.add(rhs);
return retval;

Not sure if with helps here or not, I don't use it often enough.

There are some brevity benefits you get by being able to express complex  
code as a single expression.  With does help, but can't in all  
situations.  Again, it's a matter of preference.  There's also the issue  
of shadowing.

I find myself using the chaining much more than determining the number of  
elements added.  So making that the default seems more useful.

-Steve


More information about the Digitalmars-d mailing list