Skip to content

Instantly share code, notes, and snippets.

@fcanas
Created October 7, 2017 00:19
Show Gist options
  • Save fcanas/89316d395f878c4002e8227a5378735a to your computer and use it in GitHub Desktop.
Save fcanas/89316d395f878c4002e8227a5378735a to your computer and use it in GitHub Desktop.
Abstracted average function in swift
extension Sequence where Element: BinaryFloatingPoint {
func average() -> Element {
return abstractAverage(sequence: self, sum: +, div: /)
}
}
extension Sequence where Element: SignedInteger {
func average() -> Element {
return abstractAverage(sequence: self, sum: +, div: /)
}
}
func abstractAverage<T :ExpressibleByIntegerLiteral, S :Sequence> (sequence: S, sum: (T, T)->T, div: (T, T)->T, zero: T = 0, one: T = 1) -> T where S.Element == T {
var i: T = zero
var total: T = zero
for value in sequence {
total = sum(total, value)
i = sum(i, one)
}
return div(total, i)
}
[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