[OT] Converting booleans to numbers

Timon Gehr timon.gehr at gmx.ch
Wed Sep 20 19:25:58 UTC 2017


On 19.09.2017 23:17, nkm1 wrote:
> ...
> OTOH, booleans converting to numbers is a very questionable feature. > I certainly have never seen any good use for it. ...

Actually, it is useful enough to have a Wikipedia page:
https://en.wikipedia.org/wiki/Iverson_bracket

Example of a good use:

void floodFill(dchar[][] data,dchar c,int i,int j) {
     void dfs(int a, int b) {
         if (a<0 || a >= data.length) return;
         if (b<0 || b >= data[a].length) return;
         if (data[a][b] == c) return;
         data[a][b] = c;
         foreach(i; 0 .. 4){
             dfs(a + (i==0) - (i==1),
                 b + (i==2) - (i==3));
         }
     }
     dfs(i, j);
}

unittest {
     import std.algorithm, std.conv, std.array;
     auto data = ["###.####...##"d,
                  "#....#...#..."d,
                  "..#....##.###"d,
                  "##...###...##"d,
                  "####...#....."d,
                  "#.#.#.#.#.#.#"d,
                  "#####.#######"d]
         .map!(to!(dchar[])).array;
     floodFill(data, '#', 1, 1);
     assert(data==["#############"d,
                   "#############"d,
                   "#########.###"d,
                   "########...##"d,
                   "########....."d,
                   "#.#.###.#.#.#"d,
                   "#############"d]);
}


More information about the Digitalmars-d-learn mailing list