Edit: I must not have worded it clearly enough, but I’m looking for a function like the one below, but not exactly it.
Given a list, I wanted to be able to find the index of the largest element in the list
(So, list !! (indexOfMaximum list) == maximum list)
I wrote some code that seems pretty efficient, although I feel I’m reinventing the wheel somewhere.
indexOfMaximum :: (Ord n, Num n) => [n] -> Int
indexOfMaximum list =
let indexOfMaximum' :: (Ord n, Num n) => [n] -> Int -> n -> Int -> Int
indexOfMaximum' list' currIndex highestVal highestIndex
| null list' = highestIndex
| (head list') > highestVal =
indexOfMaximum' (tail list') (1 + currIndex) (head list') currIndex
| otherwise =
indexOfMaximum' (tail list') (1 + currIndex) highestVal highestIndex
in indexOfMaximum' list 0 0 0
Now I want to return a list of the indices of the largest n numbers in the list.
My only solution is to store the top n elements in a list and replace (head list') > highestVal with a comparison across the n-largest-so-far list.
It feels like there has to be a more efficient way than to do this, and I also feel I’m making insufficient use of Prelude and Data.List. Any suggestions?
This solution associates each element with its index, sorts the list, so the smallest element is first, reverses it so the largest element is first, takes the first n elements, and then extracts the index.