Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement generic sum function for SequenceType where Generator.Element is of type Int

Tags:

generics

swift

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:

  • Type ‘S.Generator.Element’ constrained to non-protocol type ’Int’
  • Binary operator '+=‘ 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?

like image 692
Palimondo Avatar asked Dec 04 '25 14:12

Palimondo


1 Answers

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
}
like image 60
Martin R Avatar answered Dec 07 '25 08:12

Martin R