Skip to content

Instantly share code, notes, and snippets.

@rexcfnghk
Created September 26, 2021 15:03
Show Gist options
  • Save rexcfnghk/a3d43c381bd789d70022bd426f61cb75 to your computer and use it in GitHub Desktop.
Save rexcfnghk/a3d43c381bd789d70022bd426f61cb75 to your computer and use it in GitHub Desktop.
import Data.Foldable
secondLargest :: (Ord a, Foldable t) => t a -> Maybe a
secondLargest = snd . foldl' secondLargest' (Nothing, Nothing) where
secondLargest' (Nothing, Nothing) x = (Just x, Just x)
secondLargest' (Just largest, Just second) x
| x > largest = (Just x, Just largest)
| x > second = (Just largest, Just x)
| otherwise = (Just largest, Just second)
secondLargest' tuple _ = tuple
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment