I am trying to get a simple piece of functionality to work where I have a List of Lists and I want to do some mathematical operations on the data (-, + , *, /). I want the method to take any of the following types (Int, Float, Double).
here is what I have tried:
def doSomething[T](data: List[T]){
data reduceLeft(_ / _)
}
the following is displayed: value / is not a member of type parameter T.
How do I get this to work for the AnyVal types (Double, Int, Float)?
Update I tried implementing the suggestion in the following code:
def dot[T](l: List[List[T]])(implicit num: Numeric[T]) =
{
for (row <- data)
yield for(col <- l)
yield row zip col map {a => num.times(a._1 , a._2)} reduceLeft (_+_)
and get the error: type mismatch; found : a._1.type (with underlying type T) required: T
Is there any way to get around that?
For division:
def foo[T](l: List[T])(implicit num: Numeric[T]) = num match{
case i: Integral[_] => l reduceLeft (i.quot(_, _))
case fr: Fractional[_] => l reduceLeft (fr.div(_, _))}
For +, - and * it's easier (plus, minus, times respectively):
def foo[T](l: List[T])(implicit num: Numeric[T]) = l reduceLeft (num.plus(_, _))
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