[OT] Converting booleans to numbers

nkm1 t4nk074 at openmalbox.org
Wed Sep 20 21:13:58 UTC 2017


On Wednesday, 20 September 2017 at 19:25:58 UTC, Timon Gehr wrote:
> Actually, it is useful enough to have a Wikipedia page:
> https://en.wikipedia.org/wiki/Iverson_bracket

Mmmm... "The notation was originally introduced by Kenneth E. 
Iverson in his programming language APL".
APL... yeah :) Programmers didn't like it, did they. Anyway, that 
seems to be explicit notation, analogous to (cond ? 1 : 0).

> 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);
> }

I don't agree it's a good use. Actually, that seems quite 
obfuscated to me. Consider:
foreach (point; [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
     dfs(a + point[0], b + point[1]);
}
Finds some random 10 programmers and ask them what's easier to 
understand...
Also, in my experience (in C and C++) it is extremely rare for 
programmers to use booleans in arithmetic. So even if in some 
situation you would have to replace this thing with more verbose 
(i == 0 ? 1 : 0), it's no big deal.
OTOH, booleans being numbers is a source of some bugs (just like 
other cases of weak typing). Not a ton of bugs, but the utility 
of implicit conversion to numbers is so unnoticeable that I'm 
sure it's just not worth it.


More information about the Digitalmars-d-learn mailing list