Created
March 27, 2019 13:16
-
-
Save chriseidhof/8f3eeb3c32201966b8ff18a9c5ebbded 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
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