gpt4 book ai didi

haskell - 查找列表中的最大列表

转载 作者:行者123 更新时间:2023-12-03 01:37:35 26 4
gpt4 key购买 nike

我试图获取列表中总和最大的列表,然后返回该列表。但是当我用

调用该函数时
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]])

我的逻辑是这样的:我会的

  1. 对子列表中的元素求和
  2. 比较该元素以查看它是否等于列表的最大值
  3. 过滤掉不等于最大值的值

调用示例:

head (filter (\x -> (sum x) == 11) [[1,3],[4,7],[2,5]])
> [4,7]

因此,在这种情况下,我事先计算了值 11,每个元素的总和为 [4, 11, 7],它将给出总和等于最大值的值

最佳答案

Data.List 中有一个名为 maximumBy 的函数,其签名为

maximumBy :: (a -> a -> Ordering) -> [a] -> a

Data.Function具有带有签名的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 的总和大于其之前的任何值。

myMaximumBySum []     = [] -- degenerate case
myMaximumBySum [x] = x -- tautological case
myMaximumBySum (x:xs)
| sum x > sum (myMaximumBySum xs) = x
| otherwise = myMaximumBySum xs

-- or more naturally:
myMaximumBySum = foldr f []
where f x acc = if sum x > sum acc then x else acc

关于haskell - 查找列表中的最大列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49248575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com