Scala Style: Matrix (immutable over mutable) , Post-3.

vikrant
vikrant
Mar 10 · 4 min read

I observe that programmers often get intimidated by Scala and make an opinion that Scala is difficult to learn. But it is so wrong. If you understand the solution & “Keep it Simple” it is in-fact more easier to translate your thoughts to code in Scala.This is third post in series of post I am writing to share my thoughts on programming with Scala style. You can read previous two posts here & here .

In this post I will discuss Matrix. A very standard data structure and how to solve matrix problems in Scala. In my opinion coding for matrix problem is quite error prone in java or C++. For example this is how matrix multiplication will look in java.

for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++)
sum = sum + first[c][k]*second[k][d];
multiply[c][d] = sum;
sum = 0;
}
}
}

I took above code from internet. I am not sure it works or not, but it is clear so many counter and weird looking increments. This is ERROR PRONE .

We will see how Scala will make it less error prone.

But let’s start with how to define a matrix in Scala. Its simple

val squareMatrix = List.fill(4)(List.fill(4)(0)) // init by 0

val rectangularMatrix = List.fill(5)(List.fill(4)(0))

Many people use Array here, but I prefer Lists. This is more a practice for me, I want to stick to immutable.

Lets print this matrix now. You do not need those two nested loop. Scala made it simple for you. If m is a matrix, then following will print it. Just one line ..print each row.

m foreach { row => println(row.mkString(" "))}

Now lets add two matrix. We need not to define an empty matrix and then fill it, we can build matrix on the fly. If m1 and m2 are two matrixes of MxN size, you can add them like this. This code block will give you a new matrix with sum in it.

(0 until M toList) map { row =>
(0 until N toList) map { col =>
m1(row)(col) + m2(row)(col)
}
}

Lets talk about multiplication. Lets talk how it works, when we know that we can translate it to code. From here, you will know that in Matrix Multiplication we take one row from left and multiply it with all element in first column of other matrix.

This continues

So essentially we need row from first matrix and columns from second. Lets see how to get all columns. Following code will give you columns of matrix m2 ,

val m2Cols = (0 until N toList).map { col =>
(0 until M toList).map(m2(_)(col))
}

We are taking M elements (inner loop) from each column (outer loop).

Now we need to pick up each row from first matrix and just multiply it with cols we already collected from m2.

(0 until N toList) map { row =>
val m1row = m1(row)
m2Cols.map { m2col => m1row.zip(m2col).map { case (a,b) => a*b } sum}
}

Thats it, thats the multiplication.

Pro tip — If you find above difficult to understand, do this -Stop looking for your familiar java solution Read about zip . Once you do that, I guarantee you will realize that its more readable and less error prone .

Lets do few more easy things with matrix. How about getting inner matrix. One which is white in this diagram

Here is a self explaining code to get this from matrix m .

(1 until m.size-1 toList) map { r =>
(1 until m.head.size-1 toList) map { c =>
m(r)(c)
}
}

How about reversing each row ? sure

m.map(_.reverse)

Swapping columns can be tricky, right? but its not.

def swapCols(m: List[List[Int]]): List[List[Int]] = {
val rows = m.size -1
val cols = m.head.size - 1

(0 to rows toList).map { r =>
(0 to cols toList).map { c =>
m(r)(cols-c)
}
}
}

How about swapping rows? i.e. 0 swapped with M , 1 swapped with M-1 ? sure

m.reverse

swapping columns are equally simple.

def reverseCols(m: List[List[Int]]): List[List[Int]] = {
val rows = m.size -1
val cols = m.head.size - 1
(0 to rows toList).map { r =>
(0 to cols toList).map { c =>
m(rows-r)(c)
}
}
}

I hope this article helps you in your journey with Scala. In a following post I will take some more challenging problems with matrix.

Open for feedback & comments.

Cheers!

vikrant

Written by

vikrant

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade