2

问题是这样的:

编写一个接受整数列表并返回其长度和列表中第二大整数的函数。

我可以用两个函数解决这个问题,但是有没有只使用一个函数的解决方案呢?

任何帮助表示赞赏!谢谢!

4

4 回答 4

4

不要让它变得复杂。

f xs = (sort xs !! 1, length xs)

如果你选择让它变得复杂,那就以正确的方式让它变得复杂

于 2013-10-02T01:05:02.053 回答
3

编辑使用@ThomasM.DuBuisson 的建议

您可以像找到最大值一样解决这个问题:使用折叠。Max可以很简单地实现

mymaximum :: Ord a => [a] -> a
mymaximum xs = foldl searcher (head xs) xs
    where
        searcher :: Ord a => a -> a -> a
        searcher a b
            | a > b     = a
            | otherwise = b

所以我们可以通过保持两个最大值来类似地实现它(注意我们也必须用一个元组“播种”折叠):

nextmaximum :: Ord a => [a] -> a
nextmaximum xs = fst $ foldl searcher (h, h) xs
    where
        h = head xs
        searcher :: (Ord a) => (a, a) -> a -> (a, a)
        searcher (s, f) x = (min f (max s x), max f x)
于 2013-10-01T21:55:59.560 回答
2

您可以将各个功能组合在一起。这既不高效也不健壮,但它肯定很容易编写:

f xs = maximum . filter (< maximum xs) $ xs
于 2013-10-01T22:04:48.653 回答
1
head . (!!1) . group . sortBy (flip compare) $ [1,1,2,3,4,4,4,5,5,6,6,6,6]
5
于 2013-10-02T08:40:14.193 回答