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'扩展中。 –