Help me write "saveAll"

monarch_dodra monarchdodra at gmail.com
Sat Dec 22 01:05:18 PST 2012


On Saturday, 22 December 2012 at 02:58:16 UTC, Timon Gehr wrote:
> On 12/21/2012 06:01 PM, monarch_dodra wrote:
>> There are a lot of algorithms in std.algorithm that operate on
>> "foo(Range, Needles...)(Range range, Needles needles)".
>>
>> Needles can be anything, in particular, either an "element" or 
>> a "range".
>>
>> The thing is that every now and then, you want to save the 
>> entirety of
>> (the ranges) inside needles. EG, I want to be able to write:
>> foo(range, needles.saveAll);
>>
>> I'm having trouble. I did two iterations:
>>
>> //----
>> auto saveAll(Ranges...)(Ranges ranges) @property
>> {
>>     auto ret = ranges;
>>     foreach (Index, Type; Ranges)
>>         static if (isForwardRange!Type)
>>             ret[Index] = ranges[Index];
>>     return ret;
>> }
>> //----
>> This doesn't work, because: Error: functions cannot return a 
>> tuple
>> So that's that.
>> ...
>
> Use a phobos tuple?
>
> return tuple(ret)
>
> The caller can use .expand.

Victory! It works that way!

//----
auto saveAll(Stuff...)(Stuff stuff)
{
      Stuff ret = stuff;
      foreach(ref v; ret)
          ++v;
      return tuple(ret);
}

void foo(Stuff...)(Stuff stuff)
{
      bar(stuff.saveAll().expand);
}

void bar(Stuff...)(Stuff stuff)
{
      foreach (v; stuff)
          v.writeln();
}

void main()
{
      foo(1, 2, 3);
}
//----

The only limitation is that I can't declare it as a property. I
get:
main.d(11): Error: properties can only have zero, one, or two
parameter

I'd say that a bug (or at least, an unnecessary restriction), but
I can live with it.

Thankyou!


More information about the Digitalmars-d-learn mailing list