我寫了一個haskell函式來計算矩陣的行列式:
determinant :: Matrix -> Int
determinant [] = 0
determinant [[k]] = k
determinant n = sum [((-1) ^ m) * (head n !! m) * determinant (removeColumn (drop 1 n) m) | m <- [0 .. l]]
where
l = length (head n) - 1
它使用輔助函式“removeColumn”來提取列:
removeColumn :: Matrix -> Int -> Matrix
removeColumn m n = map (\row -> take (n-1) row drop n row) m
我想嘗試使用折疊重寫“行列式”函式。我一直在頭腦風暴,但我想不出如何開始。任何幫助,將不勝感激。
uj5u.com熱心網友回復:
如果不從根本上改變它,就很難轉換你的版本,因為它使用了不規則的遞回方案。對于折疊,您希望您的函式對于某些z和具有這樣的基本結構k:
determinant [] = z
determinant (x : xs) = k x (determinant xs)
您的函式在 上遞回determinant (removeColumn (drop 1 n) m),因此它顯然不兼容。
我沒有從您的函式開始,而是冒昧地根據Wikipedia 的 Leibniz 公式撰寫了一個實作:
import Data.Bifunctor (first, bimap)
-- e.g. insertEverywhere 0 [1,2] == [(0,[0,1,2]),(1,[1,0,2]),(2,[1,2,0])]
-- the tupled integer keeps track of the number of inversions
insertEverywhere :: a -> [a] -> [(Int, [a])]
insertEverywhere x =
(\(ys,yss) -> (0,(x:ys)):yss)
. foldr
(\y (ys1,ys2) -> (y:ys1, (1, y:x:ys1):map (bimap ( 1) (y:)) ys2))
([], [])
permutations :: [a] -> [(Int, [a])]
permutations =
foldr
(\x xs -> concatMap (\(n, xs) -> map (first ( n)) (insertEverywhere x xs)) xs)
[(0, [])]
determinant :: Num a => [[a]] -> a
determinant =
sum
. map (\(i,p) -> (-1) ^ i * product (zipWith (!!) p [0..]))
. perms
我想說這個實作的重要部分是使用排列作為中間結構(與反轉的數量相加)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474051.html
上一篇:重復函式時如何“保存”變數?
