-
-
Save phucledien/3d7374d48318ed476771207d6e0c5c8c to your computer and use it in GitHub Desktop.
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
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