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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With