【问题标题】:Interesting Scala typing solution, doesn't work in 2.7.7?有趣的 Scala 打字解决方案,在 2.7.7 中不起作用?
【发布时间】:2010-05-02 12:50:00
【问题描述】:

我正在尝试构建一些图像代数代码,这些代码可以处理具有不同像素类型的图像(基本上是线性像素缓冲区 + 尺寸)。为了让它工作,我定义了一个参数化的 Pixel 特征,其中包含一些应该能够与任何 Pixel 子类一起使用的方法。 (目前,我只对在相同 Pixel 类型上工作的操作感兴趣。)这里是:

trait Pixel[T <: Pixel[T]] {
    def div(v: Double): T
    def div(v: T): T
}

现在我定义了一个 Pixel 类型,它的存储基于三个双精度(基本上 RGB 0.0-1.0),我称之为 TripleDoublePixel:

class TripleDoublePixel(v: Array[Double]) extends Pixel[TripleDoublePixel] {

    var data: Array[Double] = v

    def this() = this(Array(0.0, 0.0, 0.0))

    def div(v: Double): TripleDoublePixel = {
        new TripleDoublePixel(data.map(x => x / v))
    }

    def div(v: TripleDoublePixel): TripleDoublePixel = {
        var tmp = new Array[Double](3)
        tmp(0) = data(0) / v.data(0)
        tmp(1) = data(1) / v.data(1)
        tmp(2) = data(2) / v.data(2)
        new TripleDoublePixel(tmp)
    }

}

然后我们使用 Pixels 定义一个 Image:

class Image[T](nsize: Array[Int], ndata: Array[T]) {

    val size: Array[Int] = nsize
    val data: Array[T] = ndata

    def this(isize: Array[Int]) {
        this(isize, new Array[T](isize(0) * isize(1)))
    }

    def this(img: Image[T]) {
        this(img.size, new Array[T](img.size(0) * img.size(1)))
        for (i <- 0 until img.data.size) {
            data(i) = img.data(i)
        }
    }

}

(我想我应该可以不用显式声明大小和数据,只使用在默认构造函数中命名的内容,但我还没有让它工作。)

现在我想编写代码来使用它,它不必知道像素是什么类型。例如:

def idiv[T](a: Image[T], b: Image[T]) {
    for (i <- 0 until a.data.size) {
        a.data(i) = a.data(i).div(b.data(i))
    }
}

不幸的是,这不能编译:

(fragment of lindet-gen.scala):145:
error: value div is not a member of T
                 a.data(i) = a.data(i).div(b.data(i))

我在 #scala 中被告知这对其他人有效,但那是在 2.8 上。我试图让 2.8-rc1 运行,但 RC1 不能为我编译。有没有办法让它在 2.7.7 中工作?

【问题讨论】:

  • 不是你的问题,但是三倍的 Doubles 不是比数组更合适吗?
  • 是的,我应该检查一下。

标签: scala


【解决方案1】:

您的idiv 函数必须知道它实际上会处理像素。

def idiv[T <: Pixel[T]](a: Image[T], b: Image[T]) {
    for (i <- 0 until a.data.size) {
        a.data(i) = a.data(i).div(b.data(i))
    }
}

一个普通类型参数T 将定义函数为所有可能的类型T,当然它们并不都支持div 操作。因此,您必须设置一个通用约束,将可能的类型限制为 Pixels。

(请注意,您也可以将此约束放在 Image 类上,假设图像与像素不同)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    相关资源
    最近更新 更多