Advertisement
Guest User

Untitled

a guest
Jul 30th, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. /// To use reduce() to sum a sequence, we need
  2. ///
  3. /// - a zero (identity) element
  4. /// - an addition operator
  5.  
  6. protocol Summable {
  7.  
  8. /// Identity element for this type and the + operation.
  9. static var Zero: Self { get }
  10.  
  11. /// + operator must be defined for this type
  12. func +(lhs: Self, rhs: Self) -> Self
  13. }
  14.  
  15. extension SequenceType where Generator.Element: Summable {
  16.  
  17. /// Return sum of all values in the sequence
  18. func sum() -> Generator.Element {
  19. return self.reduce(Generator.Element.Zero, combine: +)
  20. }
  21. }
  22.  
  23. // Define Zero for Int, Double, and String so we can sum() them.
  24. //
  25. // Extend this to any other types for which you want to use sum().
  26.  
  27. extension Int: Summable {
  28. /// The Int value 0
  29. static var Zero: Int { return 0 }
  30. }
  31.  
  32. extension Double: Summable {
  33. /// The Double value 0.0
  34. static var Zero: Double { return 0.0 }
  35. }
  36.  
  37. extension String: Summable {
  38. /// Empty string
  39. static var Zero: String { return "" }
  40. }
  41.  
  42.  
  43. /// A generic mean() function requires that we be able
  44. /// to convert values to Double.
  45.  
  46. protocol DoubleConvertible {
  47.  
  48. /// Return value as Double type
  49. var doubleValue: Double { get }
  50. }
  51.  
  52. // Define doubleValue() for Int and Double.
  53. //
  54. // Extend this to any other types for which you want
  55. // to use mean().
  56.  
  57. extension Int: DoubleConvertible {
  58.  
  59. /// Return Int as Double
  60. var doubleValue: Double { return Double(self) }
  61. }
  62.  
  63. extension Double: DoubleConvertible {
  64.  
  65. /// Return Double value
  66. var doubleValue: Double { return self }
  67. }
  68.  
  69.  
  70. extension CollectionType where
  71. Generator.Element: DoubleConvertible,
  72. Generator.Element: Summable,
  73. Index.Distance: DoubleConvertible {
  74.  
  75. /// Return arithmetic mean of values in collection
  76. func mean() -> Double {
  77. assert(!self.isEmpty, "cannot calculate mean of empty collection")
  78.  
  79. return self.sum().doubleValue / self.count.doubleValue
  80. }
  81. }
  82.  
  83.  
  84. // Examples
  85.  
  86. [1, 2, 3, 4, 5].sum() // 15
  87.  
  88. [1.1, 2.2, 3.3, 4.4, 5.5].sum() // 16.5
  89.  
  90. ["a", "b", "c", "d", "e"].sum() // "abcde"
  91.  
  92. [1, 2, 3, 5].mean() // 2.75
  93. [0.4, 1.2, 3.2].mean() // 1.6
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement