CTM: Exercise 3-13
Posted by Urban Hafner
The problem
Matrix operations. Assume that we represent a matrix as a list of lists of integers, where each internal list gives one row of the matrix. Define functions to do standard matrix operations such as matrix transposition and matrix multiplication.
My solution
Transposition
fun {Transpose Matrix}
{List.foldR Matrix
fun {$ R1 R2} {List.zip R1 R2 fun {$ E1 E2} E1|E2 end} end
for E in Matrix.1 collect:C do {C nil} end}
endMultiplication
fun {Multiply Matrix1 Matrix2}
if {ColumnCount Matrix1}=={RowCount Matrix2} then
TM2={Transpose Matrix2} in
for Row1 in Matrix1 collect:R do
{R for Row2 in TM2 collect:S do
{S {List.foldL {List.zip Row1 Row2 fun {$ X Y} X*Y end}
fun {$ X Y} X+Y end 0}}
end}
end
else
raise domainError end
end
endAddition
% Add any combination of matrices and numbers
fun {Add MN1 MN2}
fun {AddMatrices Matrix1 Matrix2}
{List.zip Matrix1 Matrix2
fun {$ R1 R2} {List.zip R1 R2 fun {$ E1 E2} E1+E2 end} end}
end
fun {AddNumberToMatrix Matrix Number}
for Row in Matrix collect:R do
{R {List.map Row fun {$ E} E+Number end}}
end
end
in
case MN1
of _|_ then
case MN2 of _|_ then
if {RowCount MN1}=={RowCount MN2} andthen
{ColumnCount MN1}=={ColumnCount MN2} then
{AddMatrices MN1 MN2}
else
raise differentSizes end
end
else {AddNumberToMatrix MN1 MN2} end
else
case MN2 of _|_ then {AddNumberToMatrix MN2 MN1}
else MN1 + MN2 end
end
endAuxiliary functions
fun {RowCount Matrix} {List.length Matrix} end
fun {ColumnCount Matrix} {List.length Matrix.1} end
