Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Question on Type Classes

I need to define a type class Field as follows:

trait Field[A] {  
  // Additive identity
  def zero: A

  // Multiplicative identity
  def one: A
}

The Numeric type class also provides the methods, zero and one.

I want that every class for which a Numeric instance is available can be used wherever a class with Field instance is required. For example, the following should work:

def func[F: Field](f: F) = println(f)
func(2)

Can you please suggest how to achieve this? I tried the following but it didn't work:

scala> implicit def numericToField[N](n: Numeric[N]) = new Field[N] {
     |     def zero = n.zero
     |     def one = n.one
     |   }
numericToField: [N](n: Numeric[N])java.lang.Object with Field[N]

scala> def func[F: Field](f: F) = println(f)
func: [F](f: F)(implicit evidence$1: Field[F])Unit

scala> func(2)
<console>:12: error: could not find implicit value for evidence parameter of type Field[Int]
       func(2)
           ^
like image 447
missingfaktor Avatar asked Dec 28 '22 01:12

missingfaktor


1 Answers

You've almost got it. You just need to make this small change:

scala> implicit def numericToField[N](implicit n: Numeric[N]) = new Field[N] {
 |     def zero = n.zero
 |     def one = n.one
 |   }
like image 135
derekjw Avatar answered Jan 16 '23 23:01

derekjw