functional way doing array stuff/ lambda functions
Namal via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Dec 12 19:08:33 PST 2015
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
I tried this, it compiles, but crashes when I try to run it:
object.Exception@/usr/include/dmd/phobos/std/algorithm/iteration.d(2481): Enforcement failed
----------------
??:? pure @safe void
std.exception.bailOut!(Exception).bailOut(immutable(char)[],
ulong, const(char[])) [0x43a547]
??:? pure @safe bool std.exception.enforce!(Exception,
bool).enforce(bool, lazy const(char)[], immutable(char)[], ulong)
[0x43a4c4]
??:? pure @safe int
std.algorithm.iteration.__T6reduceS305ep1247productFKxAiZ9__lambda2Z.reduce!(const(int)[]).reduce(const(int)[]) [0x43a2ed]
??:? int ep124.product(ref const(int[])) [0x439d49]
??:? _Dmain [0x43a229]
??:?
_D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv
[0x448b9a]
??:? void rt.dmain2._d_run_main(int, char**, extern (C) int
function(char[][])*).tryExec(scope void delegate()) [0x448af0]
??:? void rt.dmain2._d_run_main(int, char**, extern (C) int
function(char[][])*).runAll() [0x448b56]
??:? void rt.dmain2._d_run_main(int, char**, extern (C) int
function(char[][])*).tryExec(scope void delegate()) [0x448af0]
??:? _d_run_main [0x448a4d]
??:? main [0x4447ad]
??:? __libc_start_main [0xd9f09ec4]
More information about the Digitalmars-d-learn
mailing list