Transform a sorted range to a range of ranges of equal elements
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Dec 1 10:58:06 PST 2014
On Mon, Dec 01, 2014 at 06:37:13PM +0000, Tobias Pankrath via Digitalmars-d-learn wrote:
> Basically I need std.algorithm.uniq or std.algorithm.group, but
> instead of a single element or an element and a number I want ranges
> that each contain consecutive elements considered equal.
>
> Example: [1,1, 2,2,2,3,4,4] -> [1, 1], [2,2,2], [3], [4,4].
>
> Let's call this uniqRange. This way std.algorithm.uniq could be
> implemented as
>
> auto uniq(R, pred)(R input)
> {
> return uniqRange!pred(R).map!(r => r.front));
> }
>
> Is there any elegant way to do this with using phobos? Or do I need to
> write my own range?
Phobos git HEAD has a new range adaptor called groupBy that does what
you want:
assert([1,1,2,2,2,3,4,4].groupBy!((a)=>a).equal(
[[1,1], [2,2,2], [3], [4,4]]
))
T
--
You have to expect the unexpected. -- RL
More information about the Digitalmars-d-learn
mailing list