fork download
  1. type Number = Rational
  2. type Vector = [Number]
  3. type Row = [Number]
  4. type Matrix = [Row]
  5.  
  6. gauss :: Matrix -> Vector -> Vector
  7. gauss a b = resubstitute $ triangular $ zipWith (++) a $ map (\y -> [y]) b
  8.  
  9. triangular :: Matrix -> Matrix
  10. triangular [] = []
  11. triangular m = row:(triangular $ map f rows)
  12. where
  13. (row:rows) = rotatePivot m
  14. rotatePivot (row:rows)
  15. | (head row) /= 0 = (row:rows)
  16. | otherwise = rotatePivot (rows ++ [row])
  17. f bs
  18. | (head bs) == 0 = drop 1 bs
  19. | otherwise = drop 1 $ zipWith (-) (map (*c) bs) row
  20. where
  21. c = (head row)/(head bs)
  22.  
  23. resubstitute :: Matrix -> Vector
  24. resubstitute = reverse . resubstitute' . reverse . map reverse
  25. where
  26. resubstitute' [] = []
  27. resubstitute' (row:rows) = x:(resubstitute' $ map substituteUnknown rows)
  28. where
  29. x = (head row)/(last row)
  30. substituteUnknown (a1:(a2:as')) = ((a1-x*a2):as')
  31.  
  32.  
  33. m1 = [[1,1,0], [0,1,1], [1,0,1]] :: Matrix
  34. v1 = [2,3,4] :: Vector
  35. main = print $ gauss m1 v1
Success #stdin #stdout 0s 4716KB
stdin
Standard input is empty
stdout
[3 % 2,1 % 2,5 % 2]