functional way doing array stuff/ lambda functions

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 12 16:02:11 PST 2015


On Saturday, 12 December 2015 at 23:59:01 UTC, cym13 wrote:
> On Saturday, 12 December 2015 at 23:50:55 UTC, Xinok wrote:
>> On Saturday, 12 December 2015 at 23:36:43 UTC, cym13 wrote:
>>> ...
>>> So, in your example:
>>>
>>> int product(const ref int[] arr) {
>>>     import std.array:     array;
>>>     import std.algorithm: reduce;
>>>
>>>     arr = arr.reduce!((p, i) => p*i).array;
>>> }
>>
>> A good post overall but you got reduce wrong. In D, reduce 
>> computes and returns the result immediately, not a lazy range. 
>> The following code is correct:
>>
>> int product(const ref int[] arr) {
>>     import std.array:     array;
>>     import std.algorithm: reduce;
>>
>>     return arr.reduce!((p, i) => p*i)();
>> }
>>
>> Example: http://dpaste.dzfl.pl/fc2c2eab2d02
>
> Damn, I was certain it acted as the two others of the trio... I 
> stand corrected thanks :-)

Now that I think about it, it's true that it would make no sense 
whatsoever to return a range as reduce is typically used to 
return a single value... At least it makes perfect sense.


More information about the Digitalmars-d-learn mailing list