Skip to content

Instantly share code, notes, and snippets.

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