Michael Michael - 4 months ago 34
Scala Question

How to shift arrays and matrices in Scala

Suppose I need to shift an array of integers to left and right.

val shl : Array[Int] => Array[Int] = a => (a drop 1) :+ 0
val shr : Array[Int] => Array[Int] = a => 0 +: (a dropRight 1)


Suppose also I need to shift a matrix of integers to left and right

val shlm: Array[Array[Int]] => Array[Array[Int]] = _ map shl
val shrm: Array[Array[Int]] => Array[Array[Int]] = _ map shr


and up and down

val zeros: Int => Array[Int] = n => Array.fill(n)(0)
val shum: Array[Array[Int]] => Array[Array[Int]] = m => (m drop 1) :+ zeros(m.length)
val shdm: Array[Array[Int]] => Array[Array[Int]] = m => zeros(m.length) +: (m dropRight 1)


Now I would like to generalize
shl
and
shr
to reuse them for shifting matrix up and down. How would you do that?

Answer
import scala.reflect.ClassTag

type ArrayOp[T] = Array[T] => Array[T]

def shl[T:ClassTag](zero: T)(a: Array[T]): Array[T] = (a drop 1) :+ zero
def shr[T:ClassTag](zero: T)(a: Array[T]): Array[T] = zero +: (a dropRight 1)

val shlm: ArrayOp[Array[Int]] = _ map shl(0)
val shrm: ArrayOp[Array[Int]] = _ map shr(0)

val zeros: Int => Array[Int] = n => Array.fill(n)(0)

val shum: ArrayOp[Array[Int]] = m => shl(zeros(m.length))(m)
val shdm: ArrayOp[Array[Int]] = m => shr(zeros(m.length))(m)
Comments