Created
October 7, 2017 00:19
-
-
Save fcanas/89316d395f878c4002e8227a5378735a to your computer and use it in GitHub Desktop.
Abstracted average function in swift
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
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