我正在努力学习Haskell,我决定通过编写一个简单的函数来反演3x3矩阵。它应该很容易,但我尝试的任何东西都不会成功编译。
这是我的代码:
matInv3x3 :: [[Double]] -> [[Double]]
matInv3x3 m
| length m /= 3 = error "wrong number of rows"
| length (m !! 0) /= 3 = error "wrong number of elements in row 0"
| length (m !! 1) /= 3 = error "wrong number of elements in row 1"
| length (m !! 2) /= 3 = error "wrong number of elements in row 2"
| det == 0 = error "zero determinant"
| otherwise = mInv
where a = m !! 0 !! 0
b = m !! 0 !! 1
c = m !! 0 !! 2
d = m !! 1 !! 0
e = m !! 1 !! 1
f = m !! 1 !! 2
g = m !! 2 !! 0
h = m !! 2 !! 1
i = m !! 2 !! 2
det = a*(e*i - f*h) - b*(i*d - f*g) + c*(d*h - e*g)
A = (e*i - f*h) / det
B = -(d*i - f*g) / det
C = (d*h - e*g) / det
D = -(b*i - c*h) / det
E = (a*i - c*g) / det
F = -(a*h - b*g) / det
G = (b*f - c*e) / det
H = -(a*f - c*d) / det
I = (a*e - b*d) / det
mInv = [[A,B,C],[D,E,F],[G,H,I]]
我正在努力防范可能出错的一切:错误的列表维度和零行列式。我在“了解你......”一书中的示例之后对其进行了建模。在矩阵具有零行列式的情况下,我试图依赖于惰性求值。
GHCi不会编译它,引用第10行'='的解析错误(其中b是定义的)。我确信有一些简单,基本的东西我不知道。有人可以指出我做错了吗?
更新:
我实现了注释中提出的修复,并且还纠正了我所做的交换索引错误(之前没有发现它,因为代码无法编译)。这是固定代码,它可以正确反转3x3矩阵:
matInv3x3 :: [[Double]] -> [[Double]]
matInv3x3 m
| length m /= 3 = error "wrong number of rows"
| length (m !! 0) /= 3 = error "wrong number of elements in row 0"
| length (m !! 1) /= 3 = error "wrong number of elements in row 1"
| length (m !! 2) /= 3 = error "wrong number of elements in row 2"
| abs det < 1.0e-15 = error "zero or near-zero determinant"
| otherwise = mInv
where [[a,d,g],[b,e,h],[c,f,i]] = m
det = a*(e*i - f*h) - b*(i*d - f*g) + c*(d*h - e*g)
a' = (e*i - f*h) / det
b' = -(d*i - f*g) / det
c' = (d*h - e*g) / det
d' = -(b*i - c*h) / det
e' = (a*i - c*g) / det
f' = -(a*h - b*g) / det
g' = (b*f - c*e) / det
h' = -(a*f - c*d) / det
i' = (a*e - b*d) / det
mInv = [[a',b',c'],[d',e',f'],[g',h',i']]
答案 0 :(得分:1)
一个很好的练习是将此函数推广到任意nxn矩阵。如果您感兴趣,这里有一种计算nxn的行列式作为起点的方法。
-- Remove the nth element from a list
remove :: Int -> [a] -> [a]
remove n xs = ys ++ (tail zs)
where
(ys, zs) = splitAt n xs
-- Minor matrix of cofactor C(i,j)
minor :: Int -> Int -> [[a]] -> [[a]]
minor i j xs = remove j $ map (remove i) xs
-- The determinant of a square matrix represented as a list of lists
-- representing column vectors, that is [column].
det :: Num a => [[a]] -> a
det (a:[]) = head a
det m = sum [(-1)^i * (c1 !! i) * det (minor i 0 m) | i <- [0 .. (n-1)]]
where
c1 = head m
n = length m