我试图获取列表中包含最大金额的列表,然后返回该列表。但是当我用
调用函数时max_list [[1,2],[3,6],[10,34,5]]
它给了我错误:
Exception: a4.hs:65:1-64: Non-exhaustive patterns in function max_list
这是代码:
max_num :: [Int] -> Int
max_num [x] = x
max_num (x:xs) | (max_num xs) > x = maxVal xs
| otherwise = x
max_list :: [[Int]] -> [Int]
max_list [[a]] = head(filter (\x -> (sum_int x) == (max_num [[a]]) [[a]])
我的逻辑如下: 我会
示例电话:
head (filter (\x -> (sum x) == 11) [[1,3],[4,7],[2,5]])
> [4,7]
所以在那种情况下,我计算了手中的值11,并且每个元素的总和是[4,11,7],它将给出其总和等于最大值的值
答案 0 :(得分:7)
Data.List
中有一个名为maximumBy
的函数,带有签名
maximumBy :: (a -> a -> Ordering) -> [a] -> a
且Data.Function
的{{1}}带有签名
on
应用on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
函数(compare
),我们可以看到这正是您正在寻找的内容。
compare :: Ord a => a -> a -> Ordering
要自己实现这一点,你可以编写一个折叠,根据其总和比较每个值,递归直到import Data.List (maximumBy)
import Data.Function (on)
{- for clarity:
compare :: Ord a => b -> b -> Ordering
(compare `on`) :: Ord b => (a -> b) -> a -> a -> Ordering
compare `on` sum :: (Num a, Ord a) => [a] -> [a] -> Ordering
-- well actually [a] is t a for a foldable t, but same diff -}
result = maximumBy (compare `on` sum) [[1,2],[3,6],[10,34,5]]
的总和大于之后的任何值。
x