Advertisement
Guest User

Untitled

a guest
Dec 16th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -   Scrivere una funzione “prodM” che realizza il
  2. --  prodotto di due matrici di numeri rappresentate come liste di
  3. --  liste. La funzione deve verificare che le due matrici (cioè le
  4. --  loro rappresentazioni) siano ben formate e le loro dimensioni
  5. --  compatibili.
  6.  
  7. --Es matrici
  8. --A = [[1,0,2],[0,3,-2]]  B = [[4,1],[-2,2],[0,3]]
  9. -- AB =[[4,7],[-6,3]]
  10.  
  11. prodM :: Num a => [[a]] -> [[a]] -> [[a]]
  12. prodM xss yss
  13.     | not (areGoodFormatted xss yss) = error "matrices are bad formatted"
  14.     | otherwise = prodMat xss yss
  15.  
  16. prodMat :: Num a => [[a]] -> [[a]] -> [[a]]
  17. prodMat _ [] = []
  18. prodMat [] _ = []
  19. prodMat m1@(xs:xss) m2@(ys:yss)
  20.     | null xs = []
  21.     | otherwise = prodRowMatrix xs m2 : prodMat xss m2
  22.  
  23. prodRowMatrix :: Num a => [a] -> [[a]] -> [a]
  24. prodRowMatrix xs mat@(ys:yss)
  25.       | length ys == 0 = []
  26.       | otherwise = prodRowCol xs mat : (prodRowMatrix xs (map tail mat))
  27.  
  28.  
  29. prodRowCol :: Num a => [a] -> [[a]]  -> a
  30. prodRowCol [] _ = 0
  31. prodRowCol (x:xs) (ys:yss)
  32.         | not (null ys) = (x * head ys + prodRowCol xs yss)
  33.         | otherwise = 0
  34.  
  35. areGoodFormatted :: Num a => [[a]] -> [[a]] -> Bool
  36. areGoodFormatted [[]] [[]] = True
  37. areGoodFormatted xss yss = hasSameColSize xss && hasSameColSize yss
  38.  
  39. hasSameColSize :: Num a => [[a]] -> Bool
  40. hasSameColSize [[]] = True
  41. hasSameColSize [[_]] = True
  42. hasSameColSize (xs:xss)
  43.     |not (null xss) = length xs == length(head xss) && hasSameColSize xss
  44.     |otherwise = True
  45.  
  46. areCompatible :: Num a => [[a]] -> [[a]] -> Bool
  47. areCompatible [[]] [[]] = True;
  48. areCompatible (xs:xss) (ys:yss) = length xs == length (ys:yss)
  49.                               &&  length (xs:xss) == length ys
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement