Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Largest 2 element added in Haskell #5757

Merged
merged 2 commits into from
Jun 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import Data.List (sort)

findLargestTwoElements :: (Ord a) => [a] -> (a, a)
findLargestTwoElements xs
| length xs < 2 = error "List must contain at least two elements"
| otherwise = (largest, secondLargest)
where
sortedList = sort xs
largest = last sortedList
secondLargest = last (init sortedList)

main :: IO ()
main = do
let arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
let (largest, secondLargest) = findLargestTwoElements arr
putStrLn $ "The largest element is: " ++ show largest
putStrLn $ "The second largest element is: " ++ show secondLargest
Loading