Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active August 8, 2020 15:14
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chriseidhof/fd3e9aa621569752d1b04230f92969d7 to your computer and use it in GitHub Desktop.
Save chriseidhof/fd3e9aa621569752d1b04230f92969d7 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