Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift lazy cartesian product

I have this function in swift

func *<T1:Sequence, T2:Sequence>(lhs: T1,rhs : T2) ->
              [(T1.Iterator.Element,T2.Iterator.Element)] 
{
    let product = lhs.flatMap({ x in rhs.lazy.map{y in (x,y)}})
    return product
}

I want to make it evaluate lazy. I know i can use lhs.lazy.flatmap but what should the return type be? Or is there a better or other way to do something like this?

like image 513
Remco Greve Avatar asked Apr 10 '17 19:04

Remco Greve


1 Answers

You can create a type-erased sequence, which forward its operations to an underlying base sequence having the same Element type, hiding the specifics of the underlying sequence:

func *<T1:Sequence, T2:Sequence>(lhs: T1,rhs : T2) -> AnySequence<(T1.Iterator.Element,T2.Iterator.Element)> 
{
    return AnySequence (
        lhs.lazy.flatMap { x in rhs.lazy.map { y in (x,y) }}
    )
}

Then your code is independent of the actual implementation of lazy.flatMap and its exact return type (which may even change with newer Swift releases).

like image 168
Martin R Avatar answered Oct 01 '22 23:10

Martin R