Skip to content

Instantly share code, notes, and snippets.

@gaku-sei
Last active November 22, 2016 22:25
Show Gist options
  • Save gaku-sei/aa13f8b95ca40065f3d8a9e13f83c754 to your computer and use it in GitHub Desktop.
Save gaku-sei/aa13f8b95ca40065f3d8a9e13f83c754 to your computer and use it in GitHub Desktop.
protocol Zero {
static var zero: Self { get }
}
protocol Sumable {
static func +(lhs: Self, rhs: Self) -> Self
}
extension Int: Sumable {}
extension Double: Sumable {}
extension Int: Zero {
static let zero = 0
}
extension Double: Zero {
static let zero = 0.0
}
extension Array where Element: Sumable & Zero {
func sum() -> Element {
return self.reduce(Element.zero, +)
}
}
[1, 2, 3].sum() // 6
[1.1, 2.2, 3.3].sum() // 6.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment