Help me write "saveAll"

monarch_dodra monarchdodra at gmail.com
Fri Dec 21 09:01:13 PST 2012


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.

The next try was:
//----
void saveAll(Ranges...)(in Ranges iRanges, ref Ranges oRanges) 
@property
{
     TypeTuple!Ranges ret = ranges;
     foreach (Index, Type; Ranges)
         static if (isForwardRange!Type)
             ret[Index] = ranges[Index];
     return ret;
}
//----
This doesn't either, because a function can't have double varargs 
arguments. It's ambiguous...

So this left me with the option of just inlining into the code:
//----
         Needles savedNeedles = needles;
         foreach (Index, Type; Needles)
             static if (isForwardRange!Type)
                 savedNeedles[Index] = needles[Index];
         size_t r = startsWith!pred(haystack, savedNeedles);
//----
It works, but is kind of ugly, I'd have really wanted to be able 
to just write:
//----
         size_t r = startsWith!pred(haystack, needles.saveAll);
//----

Any thought on how do get this working?


More information about the Digitalmars-d-learn mailing list