Advertisement
Guest User

Untitled

a guest
Apr 18th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.67 KB | None | 0 0
  1. //want my library functions to use these:
  2. def times[A](x: A, y: A*)
  3. (implicit ev: Numeric[A])
  4. : A = y.fold(x)(ev.times)
  5.  
  6. def timesAB[A <: AnyVal, B <: AnyVal, AB <: AnyVal]
  7. (x:A, y:B)(implicit combine: NumericCombine.Aux[A, B, AB]): AB = {
  8.     combine.times(x,y)
  9. }
  10. def plus[A](x: A, y: A*)
  11.            (implicit ev: Numeric[A])
  12. : A = y.fold(x)(ev.plus)
  13.  
  14. def plusAB[A <: AnyVal, B <: AnyVal, AB <: AnyVal]
  15. (x:A, y:B)(implicit combine: NumericCombine.Aux[A, B, AB]): AB = {
  16.     combine.plus(x,y)
  17. }
  18.  
  19. def addTuples[A: Numeric,B: Numeric](x: (A, B), y: (A, B)): (A, B)
  20.                 = (numericOps.plus(x._1, y._1), numericOps.plus(x._2, y._2))
  21.  
  22. def accumulateWeightedValue[A <: AnyVal, B <: AnyVal, AB <: AnyVal]
  23. (accum: (A, AB), valueWithWeight: (A, B))
  24. (implicit combine: NumericCombine.Aux[A, B, AB]): (A, AB) = {
  25.     val weightedValue = combine.times(valueWithWeight.weight, valueWithWeight.value) //can already use plusAB(,)
  26.     (
  27.         combine.numericA.plus(accum.weight, valueWithWeight.weight), //ideally: plus(,) can't
  28.         combine.numericAB.plus(accum.value, weightedValue) //ideally: plus(,) can't
  29.     )
  30. }
  31.  
  32. def weightedSum[A <: AnyVal, B <: AnyVal, AB <: AnyVal]
  33. (valuesWithWeight: GenSeq[(A, B)])
  34. (implicit combine: NumericCombine.Aux[A, B, AB]):
  35. (A, AB) = {
  36.     val z: (A, AB)= (combine.numericA.zero, combine.numericAB.zero)
  37.  
  38.     valuesWithWeight.aggregate(z)(
  39.         accumulateWeightedValue[A,B,AB],
  40.         //ideally: addTuples[A,AB]
  41.         {
  42.             case ((a1, ab1), (a2, ab2)) =>
  43.                 (
  44.                     combine.numericA.plus(a1, a2),
  45.                     combine.numericAB.plus(ab1, ab2)
  46.                 )
  47.         }
  48.     )
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement