scalalinear-algebraimplicitscala-breeze

Problem with evidence parameters in breeze


I'm trying to build a DenseMatrix of Vectors in breeze. However I keep getting the error message:

could not find implicit value for evidence parameter of type breeze.storage.Zero[breeze.linalg.DenseVector[Double]]

for the line:

  val som: DenseMatrix[DenseVector[Double]] = DenseMatrix.tabulate(5, 5){ (i, j) => DenseVector.rand(20)}

Even though doing something similar with a Scala Array works fine:

val som = Array.tabulate(5, 5)((i, j) => DenseVector.rand(20))

I'm not sure what it is I'm doing wrong or what I'm missing? To be honest I don't understand what the error message is telling me... I don't do enough Scala programming to understand this? What even is an Evidence parameter and can I explicitly specify it or do I need an implicit?


Solution

  • This is because DenseMatrix.tabulate[V] firstly fills the matrix with zeroes. So there should be an instance of type class Zero for V, i.e. in our case for DenseVector[Double]. You can define it yourself e.g.

    implicit def denseVectorZero[V: Zero : ClassTag]: Zero[DenseVector[V]] =
      new Zero(DenseVector.zeros(0))
    

    i.e. if we know Zero for V then we know Zero for DenseVector[V].

    Or even easier

    implicit def ev[V: ClassTag]: Zero[DenseVector[V]] = new Zero(DenseVector(Array.empty))