scalaimplicitsspire

How do I get the implicit instance of the VectorSpace I need?


I'm trying to use spire to make a linear interpolation function I wrote more general

def interpolate(pointA: (Double,Double), pointB: (Double,Double), point: Double): Double = {
    ((pointB._1 - pointA._1) / (pointB._2 - pointA._2) * (point - pointA._2)) + pointA._1
}

I realized this could be made more general because you could interpolate elements of any vectorspace this way. So I changed it to this:

def interpolate[V,F](pointA: (V,F), pointB: (V,F), point: F)(implicit vs: VectorSpace[V,F]): V = {
    import spire.implicits._
    implicit val field: algebra.Field[F] = vs.scalar

    ((pointB._1 - pointA._1) :/ (pointB._2 - pointA._2) * (point - pointA._2)) + pointA._1
}

However when I try to use it like so:

import spire.implicits._
private val ints = interpolate((Vector(1,2,3),2.0),(Vector(4,5,6),3.0),7.0)

It says it cannot find an implicit for VectorSpace[Seq[Int],Double]. Is there a way I get the VectorSpace instance I need? Do I have to define one manually for every type I need?

I tried to define an implicit method that would produce a VectorSpace by taking an AdditiveAbGroup for the Vector type and a Field for the field type, but I couldn't get it to compile.


Solution

  • The error said, cannot find an instance for VectorSpace[Seq[Int],Double] and this is precisely the problem. Since, in a vectorspace, vectors have to be divisible by the scalar field, you cannot have a vector of ints in a VectorSpace. Also the types needed to be the same too, so

    import spire.implicits._
    private val ints = interpolate((Vector(1.0,2.0,3.0),2.0),(Vector(4.0,5.0,6.0),3.0),7.0)
    

    works fine.