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)
不錯,我甚至不知道這樣的方法存在。我甚至將它添加到我的C#'IEnumerable'擴展中。 –