Reputation: 267
I'm trying to find the greatest number from my list and also its index. For example this is my list:
list = [4.3,0.0,6.2214,9.1,1.023990433763,3.839]
I can find the greatest number with this line:
greatest = maximum list
In this example, the greatest number is 9.1, but how can I display its index (in the example, 3)?
Upvotes: 2
Views: 132
Reputation: 120711
The easiest way is to explicitly annotate the list with indices, then do the search there.
Prelude> zip [4.3,0.0,6.2214,9.1,1.023990433763,3.839] [0..]
[(4.3,0),(0.0,1),(6.2214,2),(9.1,3),(1.023990433763,4),(3.839,5)]
Because tuples Ord
lexicographically, you can actually simply use maximum
on that list:
Prelude> maximum $ zip [4.3,0.0,6.2214,9.1,1.023990433763,3.839] [0..]
(9.1,3)
This is a bit hackish though because you still have at least in principle also a comparison on the index, which you don't really want. So a cleaner way is
> :m +Data.List Data.Ord
> maximumBy (comparing fst) $ zip [4.3,0.0,6.2214,9.1,1.023990433763,3.839] [0..]
(9.1,3)
Of course, if in the end you want only the index, you can easily throw away the value:
> snd . maximumBy (comparing fst) $ zip [4.3,0.0,6.2214,9.1,1.023990433763,3.839] [0..]
3
Upvotes: 10