Reducing an array
MattCoder via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Apr 19 13:16:55 PDT 2014
On Saturday, 19 April 2014 at 17:12:10 UTC, Ali Çehreli wrote:
> On 04/19/2014 09:55 AM, MattCoder wrote:
>
> > On Friday, 18 April 2014 at 20:02:41 UTC, Tim Holzschuh via
> > Digitalmars-d-learn wrote:
> > void main(){
> > int myfilter(int a){
> > static int[] b;
>
> That static variable makes this solution non-reentrant...
Yes, you're completely right and I already knew that. But
remember Like I said previously, I would like to convert that
code to something close to "extensions" in C#, in that case I can
take the address of the array to check if it's a new Filter or
not. for example, current in D I can do this:
import std.stdio;
import std.array;
import std.range;
import std.algorithm;
void main(){
int myfilter(int[] *addr, int a){
static int[] b;
static int[] *address;
if(address != addr){
address = addr;
b.clear();
}
if(!b.canFind(a)){
b.insertInPlace(b.length, a);
return a;
}
return -1;
}
auto arr = [1,1,2,3,2,2,4,5,5,1];
auto arr2 = [3,4,3,9,9,7,4,4,4,7];
auto arrFiltered = arr.filter!(a => myfilter(&arr, a) >= 0);
writeln(arrFiltered);
auto arrFiltered2 = arr2.filter!(a => myfilter(&arr2, a) >= 0);
writeln(arrFiltered2);
}
But with extensions, the argument "address" (i.e: &arr) on the
calling of myfilter can be avoided!
Matheus.
More information about the Digitalmars-d-learn
mailing list