なんじゃくにっき

プログラミングの話題中心。

Scalaでベクトル 続き

昨日書いたScalaでベクトル
http://d.hatena.ne.jp/nanjakkun/20110601/1306929496
を可変長に。
 

package vektor.vektor

case class Vektor[T](args: T*)(implicit num: Numeric[T]) {
import num._

val x = args
val order = args.size

def checkOrder(that: Vektor[T]): Unit = {
if (this.order != that.order)
throw new IllegalArgumentException("operands must have same order")
}

// 加算
def + (that: Vektor[T]): Vektor[T] = {
checkOrder(that)

Vektor((for (i <- 0 to this.order - 1) yield (this.x(i) + that.x(i))).toSeq: _*)
}

// 減算
def - (that: Vektor[T]): Vektor[T] = {
checkOrder(that)

Vektor((for (i <- 0 to this.order - 1) yield (this.x(i) - that.x(i))).toSeq: _*)
}

// 乗算
def * (a: T): Vektor[T] = {
Vektor((for (i <- 0 to this.order - 1) yield (this.x(i) * a)).toSeq: _*)
}

// 除算 Doubleのみ
def / (a: Double): Vektor[Double] = {
Vektor((for (i <- 0 to this.order - 1) yield (this.x(i).toDouble / a)).toSeq: _*)
}

// 内積
def * (that: Vektor[T]): Vektor[T] = {
checkOrder(that)

Vektor((for (i <- 0 to this.order - 1) yield (this.x(i) * that.x(i))).toSeq: _*)
}

// 絶対値
def abs: Double = Math.sqrt(this.x.map(x => x.toDouble * x.toDouble) sum)

def toInt: Vektor[Int] = Vektor(this.x.map(_.toInt): _*)
def toLong: Vektor[Long] = Vektor(this.x.map(_.toLong): _*)
def toFloat: Vektor[Float] = Vektor(this.x.map(_.toFloat): _*)
def toDouble: Vektor[Double] = Vektor(this.x.map(_.toDouble): _*)
}