Reducing an array

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 18 13:27:20 PDT 2014


On Thu, 17 Apr 2014 09:46:25 -0400, Tim Holzschuh via Digitalmars-d-learn  
<digitalmars-d-learn at puremagic.com> wrote:

> Hi there,
>
> I try to remove all equal elements of an array, thus [2,2] --> [2].
>
> I thought this maybe would be possible with std.algorithm.reduce, but at  
> least the way I tried it doesn't work:
>
> arr.reduce( (a,b) => a != b );

reduce doesn't do what you think it does. It applies a function to all  
elements, keeping track of the result of each function call, and passing  
it to the next one.

In other words, reduce!fn(a, range) is like doing this:

fn(range[5], fn(range[4], fn(range[3], fn(range[2], fn(range[1],  
fn(range[0], a))))));

What you want is probably uniq:

http://dlang.org/library/std/algorithm/uniq.html

Note that it works on a SORTED range, so you want to sort first.

Note also that what it returns is not an array, but a lazily iterated  
range over the array. If you want another array, this is the code I would  
use:

arr.sort();
arr = arr.uniq.array();

-Steve


More information about the Digitalmars-d-learn mailing list