[OT] Converting booleans to numbers

jmh530 john.michael.hall at gmail.com
Wed Sep 20 19:47:46 UTC 2017


On Wednesday, 20 September 2017 at 19:25:58 UTC, Timon Gehr wrote:
> 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
> [snip]


While it's also possible to do this with filter, this is what I'd 
probably most often use it for.

import std.algorithm : sum;

void main()
{
     bool[] x = [true, false, true];
     int[] y = [1, 2, 3];
     y[] = x[] * y[];
     assert(sum(y[]) == 4);
}

It would be nice to be able to do:
assert(sum(x[] * y[]) == 4);


More information about the Digitalmars-d-learn mailing list