functional way doing array stuff/ lambda functions

visitor via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 13 04:41:26 PST 2015


On Sunday, 13 December 2015 at 03:08:33 UTC, Namal wrote:
> 
This works for me :

import std.stdio, std.algorithm, std.range;

int[] prim_factors(int n, const int[] P) {
     int[] v;

     P.filter!( x => x*x <= n).each!( (i) {
	while (n % i == 0) {
	    v ~= i;
	    n /= i;
             if (i == 1) break; // infinite loop otherwise !
	}
     } );

     if (n > 1) v ~= n;

     return v.sort.uniq.array;
}

void main(string[] args) {
     int[] P = [1,2,3,4,5];
     writeln( prim_factors(10, P).reduce!((r, i) => r*i)() );
}




More information about the Digitalmars-d-learn mailing list