[Issue 12409] Add "each" function as found in Ruby and jQuery

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sun Jan 11 06:54:28 PST 2015


https://issues.dlang.org/show_bug.cgi?id=12409

bearophile_hugs at eml.cc changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|RESOLVED                    |REOPENED
                 CC|                            |bearophile_hugs at eml.cc
         Resolution|FIXED                       |---

--- Comment #7 from bearophile_hugs at eml.cc ---
Reopened because I think the current design of "each" is too much bug-prone:


void main() {
    import std.stdio, std.algorithm;

    int[10] a;
    a.each!((ref x) => x++);
    a.writeln;
    a[].each!((ref x, ref i) => x = i);
    a.writeln;
    a[].each!((ref x, int i) => x = i);
    a.writeln;
    a[].each!q{ a = i };
    a.writeln;
}


[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Most Phobos functions don't accept fixed-size arrays. "each" accepts them, but
takes them by value...

And "each" accepts functions with a second "i" argument (and offers the index
"i" as in the last example), but it ignores it.

This is a mess that will cause many bugs. I suggest to tighten the semantics:
- For uniformity with Phobos it's better to not accept a fixed-size array. If
you want "each" to accept them, then take them by reference only.
- How do you use the "i" index with a lambda?
- Wrong functions probably should give a compile-time error.

--


More information about the Digitalmars-d-bugs mailing list