繁体   English   中英

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

[英]Can someone explain this simple Haskell code to me in detail

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

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)

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

有人能帮忙解决一些问题吗?

这很简单:

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

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

如果您想在评论中询问重复项,可以使用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

它从数组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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM