Scala摘要键入与制表

时间:2016-06-13 19:01:28

标签: scala scala-breeze abstract-type

我正在尝试使用Scala Breeze创建类似于Matlab的repVec函数的通用repmat函数。

首先我尝试了:

def repVec[T](in: DenseVector[T], nRow: Int): DenseMatrix[T] =
{
    DenseMatrix.tabulate[T](nRow, in.size){case (_, j) => in(j)}
}

但这给了我错误:

Error:(112, 41) No ClassTag available for T
        DenseMatrix.tabulate[T](nRow, in.size){case (_, j) => in(j)}
                                              ^
Error:(112, 41) not enough arguments for method tabulate: (implicit evidence$15: scala.reflect.ClassTag[T], implicit evidence$16: breeze.storage.Zero[T])breeze.linalg.DenseMatrix[T].
Unspecified value parameters evidence$15, evidence$16.
        DenseMatrix.tabulate[T](nRow, in.size){case (_, j) => in(j)}
                                          ^

在做了一些阅读之后,特别是here,我尝试添加一个隐含的TypeTag,如下所示:

def repVec[T](in: DenseVector[T], nRow: Int)(implicit tag: TypeTag[T]): DenseMatrix[T] =
{
    DenseMatrix.tabulate[T](nRow, in.size){case (_, j) => in(j)}
}

但我得到了同样的错误。

有关正在发生的事情的任何想法?我的用法与我可以建立的这个例子(来自链接)有什么不同?

def gratuitousIntermediateMethod[T](list:List[T])(implicit tag :TypeTag[T]) =
    getInnerType(list)

def getInnerType[T](list:List[T])(implicit tag:TypeTag[T]) = tag.tpe.toString

修改

需要ClassTagZero,这是完整的解决方案:

def repVec[T:ClassTag:Zero](in: DenseVector[T], nRow: Int): DenseMatrix[T] =
{
    DenseMatrix.tabulate[T](nRow, in.size)({case (_, j) => in(j)})
}

1 个答案:

答案 0 :(得分:1)

您需要添加隐式ClassTag,而不是TypeTag。它们是不相关的类型(有点令人沮丧)。