我需要找到矩阵中的最小元素。 我有一个解决方案,但它并不完美。
type Matrix = [[Int]]
matMin :: Matrix -> Int
matMin [] = 99999999999
matMin (xs:xss) = minimum xs `min` matMin xss
任何人都可以给我一个更好的解决方案吗?
答案 0 :(得分:10)
我能想到的最简单的事情就是matMin = minimum . concat
答案 1 :(得分:9)
查看map
功能。矩阵的最小值是每行最小值之间的最小值:
Prelude> :t minimum . map minimum
minimum . map minimum :: Ord c => [[c]] -> c
答案 2 :(得分:4)
稍微调整一下代码版本,避免使用硬编码值:
type Matrix = [[Int]]
matMin :: Matrix -> Int
matMin [] = error "min is undefined for 0x0 matrix"
matMin [xs] = minimum xs
matMin (xs:xss) = minimum xs `min` matMin xss
或者坚持使用您的方法,您可以改为使用maxBound
(因为Int
是Bounded
)。
matMin :: Matrix -> Int
matMin [] = maxBound
matMin (xs:xss) = minimum xs `min` matMin xss
事实上,这看起来像是一个折叠。
matMin = foldl' (acc x -> minimum x `min` acc) maxBound
或者如果你想得到一点毫无意义的话
matMin = foldl' (flip (min . minimum)) maxBound
-- or if you don't like the flip
matMin = foldr (min . minimum) maxBound
请注意,此模式适用于任何矩阵“折叠”。
matFoldr :: (b -> c -> c) -- how to merge the accumulator with the result of mergeCells
-> ([a] -> b) -- how to merge a row of cells
-> c -- a starting accumulator value
-> [[a]] -- the matrix to fold over
-> c
matFoldr mergeRows mergeCells start = foldr (mergeRows . mergeCells) start
matMin = matFoldr min minimum maxBound
matMax = matFoldr max maximum minBound
matSum = matFoldr (+) sum 0
matProduct = matFoldr (*) product 1
如果我们真的想要,我们甚至可以制作它,这样您就不必指定要使用的列表操作。
matEasyFold mergeRows start = matFoldr mergeRows mergeCells start
where mergeCells = foldr mergeRows start
matMin = matEasyFold min maxBound
matSum = matEasyFold (+) 0
-- etc
答案 3 :(得分:0)
非常感谢你:-p我解决得更容易,但它与Mihai的答案非常相似
matMin :: Matrix -> Int
matMin xss = minimum(map minimum xss)
感谢您的帮助。