Here's what I ended up with. (The use-case for this ended up being light-weight 
game tile placement, not image processing or anything. )

func cartesianProduct<S1: SequenceType, S2: SequenceType>(s1: S1, _ s2: S2) -> 
AnySequence<(S1.Generator.Element, S2.Generator.Element)> {
    let items = s1.lazy.flatMap({
        item1 in s2.lazy.map({
            item2 in (item1, item2)})})
    return AnySequence {items.generate()}
}

func cartesianProduct<S1: SequenceType, S2: SequenceType, S3: SequenceType>(s1: 
S1, _ s2: S2, _ s3: S3) -> AnySequence<(S1.Generator.Element, 
S2.Generator.Element, S3.Generator.Element)> {
    let items = s1.lazy.flatMap({
        item1 in s2.lazy.flatMap({
            item2 in s3.lazy.map({
                item3 in (item1, item2, item3)})})})
    return AnySequence {items.generate()}
}

I initially suggested to the person I was helping:

for y in (...) {
    for x in (...) {
      ...
    }
}

But I'm glad I got to explore several alternative approaches. Thanks all. A few 
extra notes, to summarize everything into a single post:

Joe writes: "[AnySeq/Gen] aren't on the way out. We'd like to migrate them with 
first-class language support for protocol types with associated type 
constraints, but we wouldn't eliminate the functionality."

Dmitri adds: "You can use AnySequence and AnyGenerator, but they come at a cost 
of dynamic dispatch for every call.  In this case, if you want this component 
to be suitable for performance-critical code, I would suggest to avoid them for 
now."


-- E

> On Dec 18, 2015, at 11:08 PM, Rob Mayoff via swift-users 
> <swift-users@swift.org> wrote:
> 
> 1. Can anyone recommended a better name than Cartesian? 2D doesn't work for 
> the compiler and I'm looking for something that doesn't seem 
> "floating-point"-y
> 
> "AllPairs" seems self-explanatory.
> 
> "CrossJoin" should be intuitive to anyone familiar with relational databases.
> 
> "product" sounds like it might be multiplying elements with each other.
> 
>  _______________________________________________
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to