Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a second largest number in a list in Haskell?

The question is like this:

Write a function that takes an integer list and returns its length and the second largest integer in the list.

I can solve this with two functions but is there any solution that use only one function to do it?

Any help is appreciated! Thanks!

like image 590
Zip Avatar asked Dec 05 '25 20:12

Zip


2 Answers

Don't make it complicated.

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

If you choose to make it complicated, make it complicated in the right way.

like image 92
Daniel Wagner Avatar answered Dec 08 '25 15:12

Daniel Wagner


Edited to use @ThomasM.DuBuisson's suggestion

You can solve this the same way that you could finding the max: using a fold. Max can be pretty trivially implemented with

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

So we can implement it similarly by just keeping up with the two largest values (notice that we have to "seed" the fold with a tuple as well):

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)
like image 31
bheklilr Avatar answered Dec 08 '25 15:12

bheklilr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!