Repost: make foreach(i, a; range) "just work"

Justin Whear justin at economicmodeling.com
Thu Feb 20 08:30:42 PST 2014


On Thu, 20 Feb 2014 13:04:55 +0000, w0rp wrote:
> 
> More importantly, this gets in the way of behaviour which may be
> desirable later, foreach being able to unpack tuples from ranges.
> I would like if it was possible to return Tuple!(A, B) from front() and
> write foreach(a, b; range) to interate through those thing, unpacking
> the values with an alias, so this...
> 
> foreach(a, b; range) {
> }
> 
> ... could rewrite to roughly this. (There may be a better way.)
> 
> foreach(_someInternalName; range) {
>      alias a = _someInternalName[0];
>      alias b = _someInternalName[1];
> }

Tuple unpacking already works in foreach.  This code has compiled since 
at least 2.063.2:

import std.stdio;
import std.range;
void main(string[] args)
{
    auto tuples = ["a", "b", "c"].zip(iota(0, 3));

    // unpack the string into `s`, the integer into `i`
    foreach (s, i; tuples)
        writeln(s, ", ", i);
}


More information about the Digitalmars-d mailing list