Skip to content

Instantly share code, notes, and snippets.

@ssarangi
Created July 18, 2015 06:24
Show Gist options
  • Save ssarangi/c1b2f9938d614747ca78 to your computer and use it in GitHub Desktop.
Save ssarangi/c1b2f9938d614747ca78 to your computer and use it in GitHub Desktop.
scala matrix
trait MatrixBinOps[T] {
def +(that: Matrix[T])(implicit ev: Vector[Numeric[T]]): Matrix[T]
def -(that: Matrix[T])(implicit ev: Vector[Numeric[T]]): Matrix[T]
def *(that: Matrix[T])(implicit ev: Vector[Numeric[T]]): Matrix[T]
}
trait Matrix[T] {
// def zeros(length: Int)(implicit ev: Numeric[T]): Vector[T]
// def toString(): String
}
object Matrix {
def apply[T](args: Vector[T]*): Matrix[T] = new MatrixImpl[T](args.toList)
private class MatrixImpl[@specialized(Double, Int, Float, Long)T](val _data: List[Vector[T]])
extends Matrix[T]
with MatrixBinOps[T] {
def +(that: Matrix[T])(implicit em: Vector[Numeric[T]]): Matrix[T] = new MatrixImpl[T](_data.zip(that).map(elem => elem._1 + elem._2))
def -(that: Matrix[T])(implicit em: Numeric[T]): Matrix[T] = new MatrixImpl[T](_data.zip(that).map(elem => elem._1 - elem._2))
def *(that: Matrix[T])(implicit em: Numeric[T]): Matrix[T] = new MatrixImpl[T](_data.zip(that).map(elem => elem._1 * elem._2))
// def fill(length: Int, value: T): Vector[T] = new VectorImpl[T](List.fill[T](length)(value))
// def zeros(length: Int)(implicit ev: Numeric[T]): Vector[T] = fill(length, ev.zero)
def toList(): List[Vector[T]] = _data
// override def toString(): String = "Vector(" + _data.mkString(" , ") + ")"
}
implicit def MatrixToList[T](m: Matrix[T]): List[Vector[T]] = m.toList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment