2014-01-09 250 views
0

因此,我正在学习Scala并尝试创建一个基于数组的向量类,并创建一个添加和减法运算符以添加2个向量。这是我迄今为止所做的。任何人都可以帮助弄清楚如何制作它,以便当我添加到不同长度的矢量时,它会向长度较短的数组添加“0”,以使其长度等于长度较长的数组。像添加(1, 2)(1, 2, 3)应该返回(2, 4, 3)在Scala中添加数组元素

class Wektor(private val s: Array[Double]){ 
     class LengthNotEqualException(msg:String) extends Exception(msg) 
     def get(index: Int):Double= s(index) 
     def +(that: Wektor):Wektor= 
      if(this.s.length != that.s.length) 
        throw new LengthNotEqualException("Wektory roznej dlugosci") 
      else 
      { 
      val temp= new Array[Double](this.s.length) 
      var i:Int= 0 
       for(i <- 0 until this.s.length) 
      { 
       temp(i)= this.s(i) + that.get(i) 
      } 
      new Wektor(temp) // zwraca nowy Wektor będący sumą danych wektorów 
      } 
     def -(that: Wektor):Wektor= 
      if(this.s.length != that.s.length) 
        throw new LengthNotEqualException("Wektory roznej dlugosci") 
      else 
      { 
      val temp= new Array[Double](this.s.length) 
      var i= 0 
       for(i <- 0 until this.s.length) 
      { 
       temp(i)= this.s(i) - that.get(i) 
      } 
      new Wektor(temp) // zwraca nowy Wektor będący różnicą danych wektorów 
      } 
     def *+(that:Wektor):Double= 
      if(this.s.length != that.s.length) 
        throw new LengthNotEqualException("Wektory roznej dlugosci") 
      else 
       { 
        var result:Double= 0 
        var i:Int = 0 
        for(i <- 0 until this.s.length) 
        { 
       result= result + this.s(i) * that.get(i) 
        } 
        result  // zwracany iloczyn skalarny 
       } 
     override def toString():String={ 
      var result:String="Wektor: [" 
      var i:Int= 0 
      for(i <- 0 until this.s.length) 
      { 
        result= result + this.s(i) + " " 
      } 
      result = result + "]" 
      result  // zwracana wartosc 
     } 
} 

val test= new Wektor(Array[Double](1, 2, 3,5)) 
val test2= new Wektor(Array[Double](2, 2, 2)) 
val suma= test + test2 
val roznica= test - test2 
val iloczyn= test *+ test2 
println(suma) 
println(roznica) 
println(iloczyn) 

回答

4

使用zipAll这样的:

case class Wektor(inner: IndexedSeq[Double]) { 
    def +(that: Wektor) = 
    Wektor(this.inner.zipAll(that.inner, 0.0, 0.0).map{case (a, b) => a+b}) 
    def -(that: Wektor) = 
    Wektor(this.inner.zipAll(that.inner, 0.0, 0.0).map{case (a, b) => a-b}) 
    def *+(that: Wektor) = 
    this.inner.zipAll(that.inner, 1.0, 1.0).map{case (a, b) => a*b}.sum 

    override def toString() = inner.mkString("Wektor: [", " ", "]") 
} 

val a = Wektor((1 to 5).map{_.toDouble}) 
// Wektor: [1.0 2.0 3.0 4.0 5.0] 
val b = Wektor((1 to 3).map{_.toDouble}) 
// Wektor: [1.0 2.0 3.0] 

a + b 
// Wektor: [2.0 4.0 6.0 4.0 5.0] 

a - b 
// Wektor: [0.0 0.0 0.0 4.0 5.0] 

a *+ b 
// 23.0 
+0

不错,我甚至不知道这样的方法存在。我甚至将它添加到我的C#'IEnumerable '扩展中。 –