foreach loop

wobbles via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 3 07:13:56 PST 2015


On Tuesday, 3 November 2015 at 15:10:43 UTC, wobbles wrote:
> On Tuesday, 3 November 2015 at 15:06:00 UTC, Namal wrote:
>> On Tuesday, 3 November 2015 at 14:52:19 UTC, Adam D. Ruppe 
>> wrote:
>>> On Tuesday, 3 November 2015 at 14:47:14 UTC, Namal wrote:
>>>> [...]
>>>
>>> for many of them it is as simple as:
>>>
>>> foreach(index, element; array) { }
>>
>> Thank you. I am still struggling with the functional ways of 
>> D. Now how could I write this foreach loop the functional way?
>>
>> bool[] arr = [ture, false, ture, ...];
>>
>> int count;
>> foreach(i;arr){
>>
>>   if(!i)
>>     count++;
>> }
>> writeln(count);
>
> writefln("Count is: %s", arr
>   .filter!(a => a==true)
>   .sum);
>
> // Note: std.algorithm.sum is the same as
> // std.algorithm.reduce!((a,b)=a+b);

Oh, I realise now you were counting the number of 'false' values.
I counted the true values - so the filter line is wrong here.


More information about the Digitalmars-d-learn mailing list