Last active
August 29, 2015 14:03
-
-
Save shoooe/bfc305546d25ad4af84f to your computer and use it in GitHub Desktop.
Some fun with matrices.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data Matrix a | |
= Matrix (Int, Int) [[a]] | |
deriving (Eq, Show) | |
rowIndexes :: Matrix a -> [Int] | |
rowIndexes (Matrix (_, y) _) = [0..y - 1] | |
colIndexes :: Matrix a -> [Int] | |
colIndexes (Matrix (x, _) _) = [0..x - 1] | |
row :: Int -> Matrix a -> [a] | |
row i (Matrix _ l) = l !! i | |
col :: Int -> Matrix a -> [a] | |
col i (Matrix _ l) = do | |
x <- l | |
return $ x !! i | |
matMul :: Num a => Matrix a -> Matrix a -> Matrix a | |
matMul a@(Matrix (ax, _) _) b@(Matrix (_, by) _) = | |
Matrix (ax, by) $ do | |
i <- rowIndexes a | |
return $ do | |
j <- colIndexes b | |
return $ sum $ zipWith (*) (row i a) (col j b) | |
a = | |
Matrix (2, 2) | |
[ [0, 1] | |
, [4, 2] ] | |
b = | |
Matrix (2, 2) $ | |
[ [3, 4] | |
, [5, 1] ] | |
main :: IO () | |
main = do | |
print $ matMul a b | |
-- Matrix (2,2) [[5,1],[22,18]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment