Last active
July 11, 2018 02:18
-
-
Save kristopherjohnson/7419ed4444a0ad9bb2ea to your computer and use it in GitHub Desktop.
zipWith-like function for Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Given two sequences and a function, return a sequence of results of applying | |
/// the function to sucessive elements of the sequences. | |
/// | |
/// Like Haskell's zipWith. | |
func zipCombine<S1: SequenceType, S2: SequenceType, T>( | |
sequence1: S1, | |
_ sequence2: S2, | |
combine: (S1.Generator.Element, S2.Generator.Element) -> T | |
) -> AnySequence<T> { | |
return AnySequence { () -> AnyGenerator<T> in | |
var gen1 = sequence1.generate() | |
var gen2 = sequence2.generate() | |
return anyGenerator { | |
if let elem1 = gen1.next(), elem2 = gen2.next() { | |
return combine(elem1, elem2) | |
} | |
return nil | |
} | |
} | |
} | |
// Example | |
let a1 = [10, 20, 30, 40, 50] | |
let a2 = [1, 2, 3, 4, 5] | |
let a = zipCombine(a1, a2, combine: +) | |
for n in a { print(n) } | |
// Equivalent to "let zipped = zip(a1, a2)" | |
let zipped = zipCombine(a1, a2) { ($0, $1) } | |
for pair in zipped { print("(\(pair.0), \(pair.1))") } | |
// Is this better? Worse? | |
func zipCombine2<S1: SequenceType, S2: SequenceType, T>( | |
sequence1: S1, | |
_ sequence2: S2, | |
combine: (S1.Generator.Element, S2.Generator.Element) -> T | |
) -> AnySequence<T> { | |
return AnySequence(zip(sequence1.lazy, sequence2.lazy).lazy.map(combine)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment