Skip to content

Instantly share code, notes, and snippets.

@kubukoz
Last active Dec 18, 2015
Embed
What would you like to do?
package com.kubukoz.polskibus.domain
import scala.language.postfixOps
case class Matrix[T](data: List[T]*)(implicit ev1: Numeric[T]) {
final lazy val valid = {
require(data.forall(s => s.size == data.head.size), "All rows must have the same column amount")
true
}
import ev1._
val rows = data.size
val columns = data.head.size
def *(b: Matrix[T]): Option[Matrix[T]] = columns == b.rows match {
case true if valid && b.valid => Some(Matrix(data.indices map { i =>
b.data.head.indices map { j =>
(data.head.indices map { k =>
data(i)(k) * b.data(k)(j)
}) sum
} toList
}: _*))
case _ => None
}
override def toString: String = {
valid
data.map(_.mkString(" | ")).mkString("\n")
}
def x(another: Matrix[T]) = (rows == another.rows, columns == another.columns) match {
case (true, true) if valid && another.valid =>
Some(
Matrix(
data.indices.map { i =>
data(i).indices.map { j =>
data(i)(j) * another.data(i)(j)
} toList
}: _*
)
)
case _ => None
}
def \(another: T) = {
Matrix(data.init.toList ::: List(data.last ::: List(another)): _*)(ev1)
}
def \\(another: T) = {
Matrix(data.toList ::: List(List(another)): _*)(ev1)
}
}
object MatrixMultiplication {
def main(args: Array[String]) {
implicit def numericToMatrix[T](i: T)(implicit ev1: Numeric[T]): Matrix[T] = Matrix(i :: Nil)
val a =
1 \ 2 \\
2 \ 3
val b =
2 \ 3 \\
3 \ 4
println(a * b contains (
8 \ 11 \\
13 \ 18
))
println(a x b contains (
2 \ 6 \\
6 \ 12
))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment