I have code that stores matrices of different types, e.g. m1: Array[Array[Double]], m2: List[List[Int]]. As seen, these matrices are all stored as as a sequence of rows. Any row is easy to retrieve but columns seem to me to require traversal of the matrix. I’d like to write a very generic function that returns a column from a matrix of either of these types. I’ve written this in many ways, the latest of which is:
/* Get a column of any matrix stored in rows */
private def column(M: Seq[Seq[Any]], n: Int, c: Seq[Any] = List(),
i: Int = 0): List[Any] = {
if (i != M.size) column(M, n, c :+ M(i)(n), i+1) else c.toList
This compiles however it doesn’t work: I get a type mismatch when I try to pass in an Array[Array[Double]]. I’ve tried to write this with some view bounds as well i.e.
private def column[T1 <% Seq[Any], T2 <% Seq[T1]] ...
But this wasn’t fruitful either. How come the first code segment I wrote doesn’t work? What is the best way to do this?
If you don’t care about the return type, this is a really simple way to do it: