Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created March 27, 2019 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/8f3eeb3c32201966b8ff18a9c5ebbded to your computer and use it in GitHub Desktop.
Save chriseidhof/8f3eeb3c32201966b8ff18a9c5ebbded to your computer and use it in GitHub Desktop.
struct Reducer<Element, A> {
let empty: A
let combine: (A, Element) -> A
}
func sum() -> Reducer<Int, Int> {
return Reducer(empty: 0, combine: +)
}
func count<A>() -> Reducer<A, Int> {
return Reducer(empty: 0, combine: { x, _ in x + 1})
}
extension Array {
func reduce<A>(_ reducer: Reducer<Element,A>) -> A {
return reduce(reducer.empty, reducer.combine)
}
}
func zip<El,A,B>(_ l: Reducer<El, A>, _ r: Reducer<El, B>) -> Reducer<El,(A,B)> {
return Reducer(empty: (l.empty, r.empty), combine: { x, y in
(l.combine(x.0, y), r.combine(x.1, y))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment