2017-04-10 105 views
1

我已经在迅速斯威夫特懒笛卡尔积

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 
} 

这个功能我想使它评价懒惰。我知道我可以使用lhs.lazy.flatmap,但返回类型应该是什么?还是有更好的或其他的方式来做这样的事情?

+0

选项点击'lhs.lazy.flatMap'中的'flatMap',全部显示。或者只是'print(type(of:lhs.flatMap {{in rhs.lazy.map {y in(x,y)}}))' – Alexander

+0

非常感谢。我得到LazySequence ,LazyMapSequence ,(Int,Int)>>>>。我在你看到的时候用Int来试试它。 –

回答

4

您可以创建一个type-erased sequence,其中其业务转发到具有相同Element类型的底层基础 顺序,隐藏 基础序列的细节:

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) }} 
    ) 
} 

然后你的代码是独立于实际的实现lazy.flatMap及其确切的返回类型(甚至可能会更改为 较新的Swift版本)。

0

感谢亚历山大,我想出了

func *<T1:Sequence, T2:Sequence>(lhs: T1,rhs : T2) ->  
      LazySequence<FlattenSequence<LazyMapSequence<T1, 
      LazyMapSequence<T2, (T1.Iterator.Element, T2.Iterator.Element)>>>> { 
    let product = lhs.lazy.flatMap({ x in rhs.lazy.map{y in (x,y)}}) 
    print(type(of:product)) 
    return product 
} 

这一工程,但不知是返回类型似乎有点太多对我的口味。