我正在尝试使用案例类在Scala中创建一个通用矩阵。我之所以写这里,是因为我非常感谢有见识的人对我的解决方案的任何反馈。
case class Matrix[T](data: Vector[Vector[T]]){
def foreachRowCol(f: (Int, Int, T) => Unit): Unit =
for (r <- 0 until data.size) {
for (c <- 0 until data(r).size) {
f(r, c, data(r)(c))
}
}
def map[U](f: T => U): Matrix[U] = Matrix(data.map(_.map(f)))
/** What follows are my implementations. */
/** The element at row r and column c */
def apply(r: Int, c: Int): T = data(r)(c)
/** Gives Some[T](element) at row r and column c
* if r and c are within index bounds, else None
*/
def get(r: Int, c: Int): Option[T] =
val opt: Option[T] =
if (r < data.size - 1 && c < data(r).size - 1){
Some(data(r)(c)) else None
}
opt
/** The row vector of row r */
def row(r: Int): Vector[T] = data(r)
/** The column vector of column c */
def col(c: Int): Vector[T] =
for (i <- 0 until data.size - 1){
data(i)(c)
}
/** A new Matrix with element at row r and col c updated */
def updated(r: Int, c: Int, value: T): Matrix[T] = {
val newData = {
for (i <- 0 until data.size - 1){
for (j <- 0 until data(i).size - 1){
if (r == i && j == c){
data(r)(c) = value
}
}
}
}
Matrix[T](newData)
}
object Matrix {
def fill[T](rowSize: Int, colSize: Int)(init: T): Matrix[T] =
new Matrix(Vector.fill(rowSize)(Vector.fill(colSize)(init)))
}
我有几个问题: