Is logical subsetting of an array possible ?

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 14 03:51:33 PDT 2016


On Thursday, 14 July 2016 at 10:43:12 UTC, Sahil wrote:
> This is with reference to documentation about use of array in D 
> (https://dlang.org/spec/arrays.html#array-setting).
>
> In languages tailor-made for data mining, like R, a subset of 
> an array (not necessarily contiguous values) can be extracted 
> as shown below:
>
> vec //a vector or array in R
> c(1:length(vec))[vec > 3] //extract a new array having values 
> of vec that are greater than 3.
>
> I have read about slicing, but it can only subset contiguous 
> values. Correct me if I am wrong here.
>
> How can the above functionality be achieved in D ?
> (I am totally new to D)

easily. The function you are looking for is called 'filter'

import std.algorithm;
import std.array;
int[] a = [ 4,5,8,1,3,2,9,10];
auto b = a.filter!(e => e>3).array; //b contains the elements 
4,5,8,9,10






More information about the Digitalmars-d-learn mailing list