On Tuesday, 17 October 2017 at 13:09:18 UTC, Nordlöw wrote:
I can't find any algorithm/range in Phobos that can be used to split (eagerly or lazily) a sequence using a binary predicate on adjacent elements as follows

[1,2,3,5,10,11,12,13,20,21,100].splitBy!"a + 1 != b"()

should evaluate to

[[1,2,3], [5], [10,11,12,13], [20,21], [100]]

.

Is there one?

Try this:

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

import std.typecons;

auto splitBy(alias F, R)(R range)
{
        
        auto tmp = range
                .map!(x => tuple(x, 0))
.cumulativeFold!((a,b) => tuple(b[0], (!F(a[0],b[0]))?a[1]:a[1]+1))
                .chunkBy!((a,b) => a[1] == b[1])
                .map!(x => x.map!(y => y[0]));
        
        return tmp;
}

void main()
{
[1,2,3,5,10,11,12,13,20,21,100].splitBy!((a,b) => a+1 != b)().writeln;
}


Andrea

Reply via email to