Combining "chunkBy" and "until" algorithms

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 5 15:43:49 PDT 2016


On 2016-11-05 14:57, Timon Gehr wrote:

> "chunkBy" a predicate that checks whether a line is standard. Use 'zip'
> to focus two adjacent chunks at the same time. Use 'filter' to only
> consider adjacent chunks where the first chunk consists of standard
> lines. Then extract the last line of the first chunk and combine it with
> the second chunk.
>
> import std.algorithm, std.range, std.typecons;
> import std.stdio;
>
> void main(){
>     auto data=["standard1","standard2","non-standard1","standard3",
>                "non-standard2","non-standard3","standard4"];
>     static bool isStandard(string s){
>         return s.startsWith("standard");
>     }
>     auto chunks=data.chunkBy!isStandard;
>     auto pairs=zip(chunks.save,chunks.dropOne);
>     auto result=pairs.filter!(x=>x[0][0])
>         .map!(x=>tuple(last(x[0][1]),x[1][1]));
>     result.each!(x=>writeln(x[0],", (",x[1].joiner(", "),")"));
> }
>
> auto last(R)(R r){ // missing from Phobos AFAIK
>     return zip(r.save,r.dropOne.recurrence!"a[n-1].dropOne"
>                .until!(x=>x.empty))
>         .filter!(x=>x[1].empty).front[0];
> }
>
> Prints:
> standard2, (non-standard1)
> standard3, (non-standard2, non-standard3)
>

Wow, thanks. I have to take a closer look at this to understand the code 
above.

What if I want to include all elements, i.e. "standard1" and "standard4" 
in the above example?

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list