Last active
August 8, 2020 15:14
-
-
Save chriseidhof/fd3e9aa621569752d1b04230f92969d7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extension Sequence { | |
func reduce<A>(_ initial: A, combine: (inout A, Iterator.Element) -> ()) -> A { | |
var result = initial | |
for element in self { | |
combine(&result, element) | |
} | |
return result | |
} | |
} | |
// Example implementation of `filter` using `reduce`: | |
extension Sequence { | |
func myFilter(condition: (Iterator.Element) -> Bool) -> [Iterator.Element] { | |
return reduce([]) { (result: inout [Iterator.Element], element) in | |
guard condition(element) else { return } | |
result.append(element) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment