D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 9628 - Lambda in foreach loop Vs. lambda in static foreach loop
Summary: Lambda in foreach loop Vs. lambda in static foreach loop
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords: pull, wrong-code
Depends on:
Blocks:
 
Reported: 2013-03-01 16:48 UTC by bearophile_hugs
Modified: 2013-06-08 05:25 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-03-01 16:48:17 UTC
This program shows two similar versions of the same loop:



import std.stdio, std.algorithm, std.typetuple, std.range;

void main() {
    auto items = [[10, 20], [30]];

    foreach (_; 0 .. 2) {
        foreach (sub; items) {
            iota(sub.length)
            .map!((i){ writeln(sub); return 0; })
            .array();
        }
    }

    writeln();

    foreach (_; TypeTuple!(0, 1)) {
        foreach (sub; items) {
            iota(sub.length)
            .map!((i){ writeln(sub); return 0; })
            .array();
        }
    }
}


Its output (dmd 2.063alpha):

[10, 20]
[10, 20]
[30]
[10, 20]
[10, 20]
[30]

[10, 20]
[10, 20]
[30]
[30]
[30]
[30]


Probably the two loops should give the same output.

(Also, this program can't be compiled with -inline).
Comment 1 Maxim Fomin 2013-03-02 00:27:30 UTC
Rewritten version (this can be complied with -inline):

import std.stdio, std.algorithm, std.typetuple, std.range;

auto items = [[10, 20], [30]];

void bar()
{
    foreach (int dx; 0 .. 2) {
    foreach (sub; items) {
         iota(sub.length)
         .map!((size_t i){ writeln(dx,"--", sub,"--", items); return 0; })
         .array();
    }}
}

void foo()
{
    foreach (int dx; TypeTuple!(0, 1)) {
    foreach (sub; items) {
         iota(sub.length)
         .map!((size_t i){ writeln(dx,"--", sub,"--", items); return 0; })
         .array();
    }}
}

void main() {
    bar(), writeln(), foo();
}

dx in second loop is always zero
Comment 3 github-bugzilla 2013-06-08 01:25:43 UTC
Commits pushed to master at https://github.com/D-Programming-Language/dmd

https://github.com/D-Programming-Language/dmd/commit/0ba974c94e61af361aa77756bfdcf4a9353b546f
fix Issue 9628 - Lambda in foreach loop Vs. lambda in static foreach loop

https://github.com/D-Programming-Language/dmd/commit/a8f842e12154eee7d79c1943f6e3806116cf0525
Merge pull request #2029 from 9rnsr/fix9628

Issue 9628 - Lambda in foreach loop Vs. lambda in static foreach loop
Comment 4 bearophile_hugs 2013-06-08 05:25:47 UTC
The loop can't be compiled with -inline, but the main problem seems fixed.