代码之家  ›  专栏  ›  技术社区  ›  djc

有趣的Scala打字解决方案,在2.7.7中不起作用?

  •  3
  • djc  · 技术社区  · 16 年前

    我正在尝试构建一些图像代数代码,可以处理像素类型不同的图像(基本上是线性像素缓冲区+维度)。为了实现这个功能,我定义了一个参数化的Pixel trait,其中有一些方法应该能够用于任何Pixel子类(目前,我只对在同一像素类型上工作的操作感兴趣。)这里是:

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

    现在我定义了一个单像素类型,它的存储基于三个双像素(基本上是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)
        }
    
    }
    

    然后我们使用像素定义图像:

    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))
    

    我在斯卡拉被告知这对其他人有用,但那是2.8版。我试着让2.8-rc1运行起来,但是rc1不适合我。有没有办法让它在2.7.7中工作?

    1 回复  |  直到 16 年前
        1
  •  5
  •   Dario    16 年前

    你的 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 将定义函数 对于所有可能的类型 当然,这并不都支持 div 操作。因此,您必须将可能的类型限制为 Pixel s。

    (请注意,可以对 Image 类,假设使用不同于像素的图像是没有意义的)

    推荐文章