I’m trying to write a function used in benchmarking the iteration performance of various SequenceType implementations. It should simply sum the contents of the sequence, where all elements are Ints. I’m struggling with expressing the generic constraint on the function...
func sum<S: SequenceType where S.Generator.Element: Int>(s: S) -> Int {
var sum = 0
for i in s {
sum += i
}
return sum
}
This results in following two errors:
‘S.Generator.Element’ constrained to non-protocol type ’Int’'+=‘ cannot be applied to operands of type ’Int' and ’S.Generator.Element’Is there a way to define this function to work over any SequenceType implementation, with elements specialized to Int?
The constraint should be S.Generator.Element == Int:
func sum<S: SequenceType where S.Generator.Element == Int>(s: S) -> Int {
var sum = 0
for i in s {
sum += i
}
return sum
}
Slightly more general for integer types:
func sum<S: SequenceType, T : IntegerType where S.Generator.Element == T >(s: S) -> T {
var sum : T = 0
for i in s {
sum += i
}
return sum
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With