functional programming - Ambiguous use of functions (Swift 4) -
i've been trying figure out why following code ambiguous...
public func product <t1: sequence, t2: sequence> (_ sequence1: t1, _ sequence2: t2) -> anysequence<(t1.element, t2.element)> { return anysequence( sequence1.flatmap { element1 in sequence2.map { element2 in (element1, element2) } } ) } public func product <t1: lazysequenceprotocol, t2: lazysequenceprotocol> (_ sequence1: t1, _ sequence2: t2) -> lazysequence<anysequence<(t1.element, t2.element)>> { return anysequence( sequence1.flatmap { element1 in sequence2.map { element2 in (element1, element2) } } ).lazy }
...when call 2 lazy sequences , call makeiterator
example.
_ = product([1, 2].lazy, [3, 4].lazy).makeiterator()
yet, following code doesn't have ambiguity...
public struct product2sequence <t1: sequence, t2: sequence>: sequence { public typealias element = (t1.element, t2.element) public typealias iterator = anyiterator<element> private let iterator: iterator internal init (_ sequence1: t1, _ sequence2: t2) { self.iterator = anyiterator( sequence1.flatmap { element1 in sequence2.map { element2 in (element1, element2) } }.makeiterator() ) } public func makeiterator () -> iterator { return self.iterator } } public struct lazyproduct2sequence <t1: lazysequenceprotocol, t2: lazysequenceprotocol>: lazysequenceprotocol { public typealias element = (t1.element, t2.element) public typealias iterator = anyiterator<element> private let iterator: iterator internal init (_ sequence1: t1, _ sequence2: t2) { self.iterator = anyiterator( sequence1.flatmap { element1 in sequence2.map { element2 in (element1, element2) } }.makeiterator() ) } public func makeiterator () -> iterator { return self.iterator } } public func product <t1: sequence, t2: sequence> (_ sequence1: t1, _ sequence2: t2) -> product2sequence<t1, t2> { return product2sequence(sequence1, sequence2) } public func product <t1: lazysequenceprotocol, t2: lazysequenceprotocol> (_ sequence1: t1, _ sequence2: t2) -> lazyproduct2sequence<t1, t2> { return lazyproduct2sequence(sequence1, sequence2) }
...when call 2 lazy sequences , call makeiterator
example.
_ = product([1, 2].lazy, [3, 4].lazy).makeiterator()
my reasoning lazy sequence conforms both lazysequenceprotocol
, sequence
type system doesn't know product
choose. definition second version should not work.
i'm using swift 4.0.
what makes second version work?
Comments
Post a Comment