Matrix multiplication: Difference between revisions

Added Scala
m (Fixed lang tags.)
(Added Scala)
Line 838:
end
end</lang>
 
=={{header|Scala}}==
{{works with|Scala|2.8}}
Assuming an array of arrays representation:
 
<lang scala>def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = {
import n._
for (row <- a)
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</lang>
 
For any subclass of <code>Seq</code> (which does not include Java-specific arrays):
 
<lang scala>def mult[A, CC[X] <: Seq[X], DD[Y] <: Seq[Y]](a: CC[DD[A]], b: CC[DD[A]])
(implicit n: Numeric[A]): CC[DD[A]] = {
import n._
for (row <- a)
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</lang>
 
Examples:
 
<pre>
scala> Array(Array(1, 2), Array(3, 4))
res0: Array[Array[Int]] = Array(Array(1, 2), Array(3, 4))
 
scala> Array(Array(-3, -8, 3), Array(-2, 1, 4))
res1: Array[Array[Int]] = Array(Array(-3, -8, 3), Array(-2, 1, 4))
 
scala> mult(res0, res1)
res2: Array[scala.collection.mutable.GenericArray[Int]] = Array(GenericArray(-7, -6, 11), GenericArray(-17, -20, 25))
 
scala> res0.map(_.toList).toList
res5: List[List[Int]] = List(List(1, 2), List(3, 4))
 
scala> res1.map(_.toList).toList
res6: List[List[Int]] = List(List(-3, -8, 3), List(-2, 1, 4))
 
scala> mult(res5, res6)
res7: Seq[Seq[Int]] = List(List(-7, -6, 11), List(-17, -20, 25))
</pre>
 
A fully generic multiplication that returns the same collection as received is possible,
but much more verbose.
 
=={{header|Scheme}}==
Anonymous user