Skip to content

Instantly share code, notes, and snippets.

@shoooe
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoooe/bfc305546d25ad4af84f to your computer and use it in GitHub Desktop.
Save shoooe/bfc305546d25ad4af84f to your computer and use it in GitHub Desktop.
Some fun with matrices.
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