-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTeste.hs
50 lines (38 loc) · 1.6 KB
/
Teste.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module Teste where
import System.IO
import Data.Char
import Data.List
import System.Random (randomRIO)
main = do
putStrLn "Enter first matrix (put // to denote row breaks):"
m1 <- getLine
putStrLn "Enter second matrix (put // to denote row breaks):"
m2 <- getLine
putStr $ doMult m1 m2
doMult :: String -> String -> String
doMult x y = if (length (head (buildMatrix (getRowLength x) (parseMatrix x)))) /= (length (buildMatrix (getRowLength y) (parseMatrix y)))
then "\nError: dimensions do not match\n"
else "\nResult:\n" ++ (printMatrix $ matrixMult (buildMatrix (getRowLength x) (parseMatrix x)) (buildMatrix (getRowLength y) (parseMatrix y)))
printMatrix :: Show a => [[a]] -> [Char]
printMatrix [] = ""
printMatrix (x:xs) = printRow x ++ "\n" ++ printMatrix xs
printRow :: Show a => [a] -> [Char]
printRow [] = ""
printRow (x:xs) = show x ++ " " ++ printRow xs
getRowLength :: String -> Int
getRowLength x = head $ findIndices (== "//") $ words x
parseMatrix :: (Num b, Read b) => String -> [b]
parseMatrix x = map (+0) $ map read $ filter (/= "//") $ words x
buildMatrix :: Num a => Int -> [a] -> [[a]]
buildMatrix _ [] = []
buildMatrix y x = take y x : buildMatrix y (drop y x)
matrixMult :: Num a => [[a]] -> [[a]] -> [[a]]
matrixMult x y = matrixMultT x $ transpose y
matrixMultT :: Num a => [[a]] -> [[a]] -> [[a]]
matrixMultT [] _ = []
matrixMultT (a:as) b = calcRow a b : matrixMultT as b
calcRow :: Num a => [a] -> [[a]] -> [a]
calcRow _ [] = []
calcRow a (b:bs) = calcCell a b : calcRow a bs
calcCell :: Num a => [a] -> [a] -> a
calcCell col row = foldl1 (+) $ zipWith (*) col row