有人可以向我详细解释这个简单的Haskell代码

时间:2016-10-08 14:11:04

标签: haskell

我在一个非常古老的帖子上发现了这个,并且不想在那里问,因为它可能永远得不到答案。

f xs = maximum . filter (< maximum xs) $ xs

它看起来像是

  • 获取已过滤列表的最大值
  • 小于列表的最大值

secondLargest :: (Num a, Ord a) => [a] -> a
secondLargest [] = error "Empty List"
secondLargest [x] = error "Empty List"
secondLargest xs
    | ((maximum . filter (< maximum xs) $ xs) >= (maximum xs)) = maximum xs
    | otherwise = (maximum . filter (< maximum xs) $ xs)

上面的代码就是我现在正在使用的代码。基本上我无法对列表进行排序,只要最大和第二大元素不相同,上面的代码就会找到第二大元素。

任何人都能帮忙解决一些问题吗?

3 个答案:

答案 0 :(得分:4)

这很简单:

f xs = maximum . filter (< maximum xs) $ xs

我们假设xs = [1,2,3,4,5]。因此,maximum xs = 5。因此,我们有:

f [1,2,3,4,5] = maximum . filter (< 5) $ [1,2,3,4,5]

接下来,我们会过滤掉低于5的所有元素。因此我们得到:

f [1,2,3,4,5] = maximum $ [1,2,3,4] -- notice that 5 is no more in the list

最后,我们得到剩余元素的最大值:

f [1,2,3,4,5] = 4

这恰好是原始列表中的第二大元素。

答案 1 :(得分:3)

如果您想在评论中询问重复项,可以使用Data.List.delete代替filter删除最大的元素。这只会删除它的一个实例:

import Data.List (delete)

f xs = maximum . delete (maximum xs) $ xs

这会产生:

λ. f [1,2,3,4,5]
4
λ. f [1,2,3,4,5,5]
5

当然,这仅适用于长度为2或更长的列表。如果你想考虑所有情况,所以函数是完全的,你可以这样做:

f xs | length xs >= 2 = maximum . delete (maximum xs) $ xs
     | null xs        = 0   -- default case when the list is empty
     | otherwise      = maximum xs

要在没有导入的情况下执行此操作,您可以手动实现delete

delete :: Eq a => a -> [a] -> [a]
delete x [] = []
delete x (y:ys) | x == y    = ys
                | otherwise = y : delete x ys

答案 2 :(得分:1)

它从数组xs中找到第二大数字,以便将其分解。

let xs = [1, 2, 3, 4]
let a = filter (< maximum xs) xs
-- a is an array of all elements from 'xs' except of the max elem of 'xs'
-- which is [1, 2, 3]

let b = maximum (a) -- gets the largest elem of a
--  b is th largest element of 'a'
-- which is 3

并在其上应用maximum会产生第二大elem