-
-
Save sindresorhus/0f5981d6c583424ad6d963dba0d78616 to your computer and use it in GitHub Desktop.
Abstracted average function in Swift
This file contains hidden or 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 where Element: ExpressibleByIntegerLiteral { | |
private func abstractAverage<T>(sum: (T, T) -> T, div: (T, T) -> T) -> T where Element == T { | |
var i: T = 0 | |
var total: T = 0 | |
for value in self { | |
total = sum(total, value) | |
i = sum(i, 1) | |
} | |
return div(total, i) | |
} | |
} | |
extension Sequence where Element: BinaryFloatingPoint { | |
func average() -> Element { | |
return abstractAverage(sum: +, div: /) | |
} | |
} | |
extension Sequence where Element: BinaryInteger { | |
func average() -> Element { | |
return abstractAverage(sum: +, div: /) | |
} | |
} | |
[1.0, 2.2, 3.0].average() | |
[1, 2, 3].average() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment