【问题标题】:Scala convert type parameter to DoubleScala 将类型参数转换为 Double
【发布时间】:2017-02-13 16:00:02
【问题描述】:

我已经定义了这个类:

class LinearEquations[T <% Double](var y: MLVector[T],var rows: MLMatrix[T]) {
def largestPivot(p: Int): Int = {
    var pivot = rows(p)(p).abs //Error here: value abs is not a member of type parameter T
    //more code
}

在哪里

type MLMatrix[T] = Array[Array[T]]

现在,在另一个类中,我正在创建对象 LinearEquations(假设 MLMatrix 填充了 Doubles):

var rows = new MLMatrix[Double](4)//now fill with Doubles
val le = new LinearEquations(y, rows)

我必须进行某种类型的隐式转换,但我不知道该怎么做。构造函数接收一个类型参数,但是当我实例化该类时,我传递了一个 Double。

提前致谢,

【问题讨论】:

  • 请在minimal reproducible example 上发布您的问题。什么是y 和rows,它们是在哪里创建的?此外,不推荐使用视图边界。
  • 相当多的陈述,毫无疑问。问个问题怎么办?你有错误吗?有什么问题?
  • 看看我写的怎么样。你没看到错误吗?值 abs 不是类型参数 T 的成员
  • 对不起,我错过了。可能是因为你把它当作代码中的注释。

标签: scala


【解决方案1】:

代码:

10.0.abs

由于隐式转换为在Predef 中定义的RichDouble 类型,因此工作:

@inline implicit def doubleWrapper(x: Double)   = new runtime.RichDouble(x)

但是,在某些情况下,由于某些原因,编译器不能像对待Double 一样对待T。

虽然有解决此问题的方法,例如类型类:

trait MathsOps[T] {

  def abs(num: T): T
}

implicit object DoubleOps extends MathOps[Double] {
   def abs(num: Double) = num.abs
}

class LinearEquations[T : MathsOps](var y: MLVector[T], var rows: MLMatrix[T]) {
def largestPivot(p: Int): Int = {
    var pivot = implicitly[MathOps[T]].abs(rows(p)(p))
    //more code
}

这可以通过为您可能使用的所有可能的T 提供新的隐式来轻松扩展。

要恢复语法,您可以定义另一个隐式类:

implicit class RichMathSyntax[T : MathOps](value: T) {

  def abs = implicitly[MathOps[T]].abs(value)
}

这应该适用于您可能想要传递给LinearEquations 的任何数字类型。

【讨论】:

  • 这就是我想要的。真棒答案!谢谢。
【解决方案2】:

试试这个:

  class LinearEquations[T <% Double](var y: Array[Array[T]], var rows: Array[Array[T]]) {
    def largestPivot(p: Int): Int = {
      var pivot = rows(p)(p) //Error here: value abs is not a member of type parameter T
      val res: Double = scala.math.abs(pivot)
      //more code
      0
    }
  }

它为我编译

【讨论】:

  • 这行得通,但我一直在寻找一种更 scala 的方式来做到这一点。谢谢
  • 你可能想看看 Spire 开源数学项目:github.com/non/spire 它有很多很好的通用数学代码。我自己使用它并且对它很满意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2017-02-08
  • 2017-12-29
相关资源
最近更新 更多