Is there a better way to write this split functionality?

bearophile bearophileHUGS at lycos.com
Mon May 9 03:04:04 PDT 2011


Andrej Mitrovic:

> Is there a better way to do this, some std.range/algorithm function I don't know of?

Maybe this does what you want, but it's not very good:

import std.stdio, std.algorithm;

void main() {
    auto arr = [64, 64, 64, 32, 31, 16, 32, 33, 64];

    int last = 0;
    foreach (g; group!q{ (a < 32) == (b < 32) }(arr)) {
        writeln(arr[last .. last+g[1]]);
        last += g[1];
    }
}


With the change to group() Andrei talks about the code becomes a little better (untested code):

import std.stdio, std.algorithm;

void main() {
    auto arr = [64, 64, 64, 32, 31, 16, 32, 33, 64];

    foreach (g; group!q{ (a < 32) == (b < 32) }(arr))
        writeln(g[1]);
}


In Python groupby uses a key mapping function, like D schwartzSort():

>>> from itertools import groupby
>>> arr = [64, 64, 64, 32, 31, 16, 32, 33, 64]
>>> [list(g) for h,g in groupby(arr, key = lambda x: x < 32)]
[[64, 64, 64, 32], [31, 16], [32, 33, 64]]


If group uses a key mapping function as schwartzSort() the code improves (untested):

import std.stdio, std.algorithm;

void main() {
    auto arr = [64, 64, 64, 32, 31, 16, 32, 33, 64];

    foreach (g; group!q{ a < 32 }(arr))
        writeln(g[1]);
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list