使用 Tabulate 的 Scala 抽象类型
Scala Abstract Typing with Tabulate
我正在尝试使用 Scala Breeze 创建一个类似于 Matlab 的 repmat
函数的通用 repVec
函数。
首先我尝试了:
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: scala.reflect.ClassTag[T], implicit evidence: breeze.storage.Zero[T])breeze.linalg.DenseMatrix[T].
Unspecified value parameters evidence, evidence.
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)}
}
但是我得到了同样的错误。
对发生的事情有什么想法吗?我的用法与这个我可以构建得很好的示例(来自 link)有何不同?
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
编辑:
需要 ClassTag
和 Zero
,这里是完整的解决方案:
def repVec[T:ClassTag:Zero](in: DenseVector[T], nRow: Int): DenseMatrix[T] =
{
DenseMatrix.tabulate[T](nRow, in.size)({case (_, j) => in(j)})
}
您需要添加隐式 ClassTag,而不是 TypeTag。它们是不相关的类型(有点令人沮丧)。
我正在尝试使用 Scala Breeze 创建一个类似于 Matlab 的 repmat
函数的通用 repVec
函数。
首先我尝试了:
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: scala.reflect.ClassTag[T], implicit evidence: breeze.storage.Zero[T])breeze.linalg.DenseMatrix[T].
Unspecified value parameters evidence, evidence.
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)}
}
但是我得到了同样的错误。
对发生的事情有什么想法吗?我的用法与这个我可以构建得很好的示例(来自 link)有何不同?
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
编辑:
需要 ClassTag
和 Zero
,这里是完整的解决方案:
def repVec[T:ClassTag:Zero](in: DenseVector[T], nRow: Int): DenseMatrix[T] =
{
DenseMatrix.tabulate[T](nRow, in.size)({case (_, j) => in(j)})
}
您需要添加隐式 ClassTag,而不是 TypeTag。它们是不相关的类型(有点令人沮丧)。