Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding index of element in a list in Haskell?

I have a function in Haskell which finds the maximum value of an exponentiation from a list:

prob99 = maximum $ map (\xs -> (head xs)^(head (tail xs))) numbers 

What I need to find is the location of this maximum value in the resultant list. How would I go about this?

Edit: I found a solution that goes like this:

n = [[519432,525806],[632382,518061].... prob99b [a,b] = b* (log a) answer = snd $ maximum (zip  (map prob99b n) [1..]) 
like image 280
Jonno_FTW Avatar asked Sep 30 '09 09:09

Jonno_FTW


People also ask

How do you find the index of an element in a list of lists?

To find the (row, column) index pair of an element in a list of lists, iterate over the rows and their indices using the enumerate() function and use the row. index(x) method to determine the index of element x in the row .

How do you find the index of an element?

indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Which operator is used to get an element out of a list by index in Haskell?

Look here, the operator used is !! . I.e. [1,2,3]!! 1 gives you 2 , since lists are 0-indexed.


1 Answers

How to find the index of the maximum element? How about trying all indexes and checking whether they are the maximum?

ghci> let maxIndex xs = head $ filter ((== maximum xs) . (xs !!)) [0..] 

But this sounds like something for which a function already exists. My code will be more readable, maintainable, and probably even more efficient, if I used the existing function.

FYI, you can also ask Hoogle that can search by Haskell type signatures (as Will suggested):

$ hoogle "Ord a => [a] -> Int" | head  <Nothing relevant>  $ # hmm, so no function to give me the index of maximum outright, $ # but how about finding a specific element, and I give it the maximum? $ hoogle "a -> [a] -> Int" | head Data.List elemIndex :: Eq a => a -> [a] -> Maybe Int Data.List elemIndices :: Eq a => a -> [a] -> [Int] 
like image 110
yairchu Avatar answered Sep 29 '22 17:09

yairchu