Cartesian product of ranges?

Timon Gehr timon.gehr at gmx.ch
Wed Dec 14 13:21:30 PST 2011


On 12/14/2011 09:14 PM, Justin Whear wrote:
> I've looked through std.algorithm and std.range, but haven't found anything
> to compute the Cartesian product of several ranges. I have the nagging
> feeling that this can be accomplished by combining several of the range
> transformations in the standard library.
>
> What I'm after is something like this:
>
> alias Tuple!(int, string) P;
> assert(equal(
> 	cartesianProduct([1, 2], ["a", "b"]),
> 	[ P(1, "a"), P(1, "b"), P(2, "a"), P(2, "b") ]
> ));
>

auto cartesianProduct(R,S)(R r, S s)if(isInputRange!R && isForwardRange!S){
     struct CartesianProduct{
         private{R r; S s, startS;}
         this(R r, S s){this.r=r; this.s=s; startS=this.s.save;}
         @property auto front(){return tuple(r.front, s.front);}
         @property bool empty(){return r.empty;}
         void popFront(){
                 s.popFront();
                 if(s.empty){
                     s = startS.save;
                     r.popFront();
                 }
         }
         static if(isForwardRange!R):
         @property auto save(){return typeof(this)(r.save, s.save);}
     }
     return CartesianProduct(r,s);
}


More information about the Digitalmars-d-learn mailing list