7

double、int、booleanのいずれかになり得るSparseVector[T]クラスを作成したいと思います。T

クラスは配列によってサポートされません(スパースデータ構造が必要なため)が、AnyVal型の空の配列を作成すると、要素がデフォルト値に初期化されることを確認しました。例えば:

 scala> new Array[Int](10)
 res0: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

 scala> new Array[Boolean](10)
 res1: Array[Boolean] = Array(false, false, false, false, false, false, false, false, false, false)

 scala> new Array[Double](10) 
 res2: Array[Double] = Array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)

このデフォルト値をクラスに含めるにはどうすればよいですか?私が取得したい動作は次のとおりです。

val v = new SparseVector[Double](100)
println( v(12) ) // should print '0.0'
val w = new SparseVector[Boolean](100)
println( v(85) ) // should print 'false'

ありがとう

4

4 に答える 4

7

コンストラクターに 2 番目のパラメーターとして暗黙の引数を追加できます。

class SparseVector[A](size: Int) (implicit default: () => A) {
  private var storage = scala.collection.mutable.Map[Int, A]()
  def apply(i: Int) = storage.getOrElse(i, default())
  def update(i: Int, v: A) = storage.update(i, v)
}

implicit def strDefault(): String = "default"

そして、気になる型に暗黙を提供します。これにより、呼び出し元は、独自のデフォルト値を次のように渡すことで、独自のデフォルトを提供することもできます。

val sparseWithCustomDefault = new SparseVector[String](10) (() => "dwins rules!");
于 2009-12-04T19:06:03.340 に答える
4

マニフェストを使用して for と同じデフォルトを取得できますArray。これにより、独自の暗黙を提供する必要がなくなります。残りのコードは David Winslow から再度借ります。

class SparseVector[T](size: Int)(implicit manifest: Manifest[T]) {
    private val default = manifest.newArray(1)(0)
    private var storage = scala.collection.mutable.Map[Int, T]()
    def apply(i: Int) = storage.getOrElse(i, default)
    def update(i: Int, v: T) = storage.update(i, v)
}

それからちょうど、

val v = new SparseVector[Int](100)
println( v(12) ) // prints '0'

于 2009-12-05T11:47:19.960 に答える
0

David の SparseVector クラスを再利用すると、次のようなものを使用できます。

class SparseVector[T](size: Int, default: T = 0) {
  private var storage = scala.collection.mutable.Map[Int, T]()
  def apply(i: Int) = storage.getOrElse(i, default)
  def update(i: Int, v: T) = storage.update(i, v)
}

object SparseVector {
  implicit def svInt2String(i: Int) = "default"
  implicit def svInt2Boolean(i: Int = false
}

暗黙をインポートする必要がありますが、これは残念ですが、これにより次のことが得られます。

import SparseVector._    

val v = new SparseVector[Int](100)
println( v(12) ) // prints '0'
val w = new SparseVector[Double](100)
println( w(12) ) // prints '0.0'
val x = new SparseVector[Boolean](100)
println( x(85) ) // prints 'false'
val y = new SparseVector[String](100)
println( y(85) ) // prints 'default'
于 2009-12-05T10:04:48.283 に答える