1

I am writing a number of utility functions that all have the same genericity in their type parameters. They all have implicit parameters and I'm also using the Aux pattern to relate some of these types. Here is the signature for some of these functions:

def accumulateWeightedValue[A, B, AB]
            (accum: (A, AB), valueWithWeight: (A, B))
            (implicit combine: NumericCombine.Aux[A, B, AB]): (A, AB) ={...}

def weightedSum[A, B, AB]
            (valuesWithWeight: GenSeq[(A, B)])(implicit combine: NumericCombine.Aux[A, B, AB]):
            (A, AB) = {...}

def weightedAverageFloat[A, B, AB]
            (valuesWithWeight: GenSeq[(A, B)])(implicit combine: NumericCombine.Aux[A, B, AB])
            : Option[Float]

These functions have different explicit argument types and different return types. but they all share the same dependence on types: [A, B, AB] types and have the same implicit arguments.

Is there a way of somehow factoring out all the type dependency information to make the functions look less tedious, specially as the number of such functions grows? ie have instead:

def accumulateWeightedValue(accum: (A, AB), valueWithWeight: (A, B)): (A, AB)

def weightedSum(valuesWithWeight: GenSeq[(A, B)]):(A, AB)

def weightedAverageFloat(valuesWithWeight: GenSeq[(A, B)]): Option[Float]

Obvious option would be to make them all methods of a class Utility parameterised by [A, B, AB] but that would mean that my functions will no longer be callable as standalone functions foo().

There is perhaps potential with doing some tricks with the companion object and duplicating the fully templatised version of these functions in the companion object and doing some implicit redirection and some refactoring to make Utility.foo() call the method foo() on the correct implicit instance of this class. I am not however too sure about the pros and cons of this approach.

Is there any alternative to the suggested approach?

FYI, here is the context of this question and you can see a demo of the usage of the functions above in here.

Community
  • 1
  • 1
Maths noob
  • 1,684
  • 20
  • 42

0 Answers0