1
votes

I want to be able to define the following function in Scala:

import Numeric.Implicits._
def f[T:Numeric](a:T) = a*2

but I get the error

error: could not find implicit value for parameter num: scala.math.Numeric[Any]
       def f[T:Numeric](a:T) = a*2
                               ^

I can get it to work with an implicit n:Numeric[T] argument and n.fromInt, but readability suffers. (The real code I'm trying to write is more complicated than this.)

I tried to define an implicit conversion from Int to Numeric[T]:

implicit def intToNumericT[T](x:Int)(implicit n:Numeric[T]):T = n.fromInt(x)

but that doesn't help. Is there a way to get the above code to work?

3

3 Answers

1
votes

You could pimp a multiply-by-int method onto numeric types:

import Numeric.Implicits._
implicit class RichNumeric[A](val a: A) extends AnyVal {
  def *(i: Int)(implicit n: Numeric[A]) = n.times(a, n.fromInt(i))
}
def f[T: Numeric](a: T) = a * 2
1
votes

How about:

implicit class NumericInt(x:Int){
   def nu[T](implicit n: Numeric[T])  = n.fromInt(x)
}
import Numeric.Implicits._

def f[T: Numeric](a: T) = a * 2.nu

Example:

scala> def f[T: Numeric](a: T) = a * 2.nu
f: [T](a: T)(implicit evidence$1: Numeric[T])T

scala> f(5)
res0: Int = 10
1
votes

I think that definition should be as follows:

import Numeric.Implicits._

def f[T <% Numeric[T]#Ops](a: T)(implicit f: Int => T) = a * 2

println(f(5)) // 10
println(f(BigDecimal(7))) // 14
println(f(1.7)) // 3.4