Haskell  언어로 행렬 곱셈하는 간단한 소스

(정수로 이루어진 행렬, 분수로 이루어진 행렬, 부동소수점수로 이루어진 행렬, 복소수로 이루어진 행렬 들릐 곱셈을 처리합니다.) 

 

-- Filename: testMatrixMultiplication.hs
--
-- 참조: http://rosettacode.org/wiki/Matrix_multiplication#Haskell

module Main where

import Data.Complex
import Data.Ratio
import Text.Printf
import Data.List 


-- 행렬 곱셉 함수
mmult :: Num a => [[a]] -> [[a]] -> [[a]] 
mmult a b = [ [ sum $ zipWith (*) ar bc | bc <- (transpose b) ] | ar <- a ]


-- 사용 예
main :: IO ()
main = do
    -- matrix of integers
    let test = [[1, 2], 
                  [3, 4]] `mmult` [[-3, -8, 3],
                                            [-2,  1, 4]]
    print test

    -- matrix of floats
    let test = [[1.0, 2.0], 
                    [3.0, 4.0]] `mmult` [[-3, -8, 3],
                                                   [-2,  1, 4]]
    print test

    -- matrix of fraction
    let test = [[(1 % 1),  (2 % 1)], 
                    [(3 % 1), (4 % 1)]] `mmult` [[-3, -8, 3],
                                                                [-2,  1, 4]]
    print test

    -- matrix of complex numbers
    let test = [[(1 :+ 1),  (2 :+ 1)], 
                    [(3 :+ 1), (4 :+ 1)]] `mmult` [[-3, -8, 3],
                                                                [-2,  1, 4]]
    print test

{-
실행: runhaskell testMatrixMultiplication.hs
출력:
-------------------------------------------
[[-7,-6,11],[-17,-20,25]]
[[-7.0,-6.0,11.0],[-17.0,-20.0,25.0]]
[[(-7) % 1,(-6) % 1,11 % 1],[(-17) % 1,(-20) % 1,25 % 1]]
[[(-7.0) :+ (-5.0),(-6.0) :+ (-7.0),11.0 :+ 7.0],[(-17.0) :+ (-5.0),(-20.0) :+ (-7.0),25.0 :+ 7.0]]
-}

 

 

 

Posted by Scripter
,