tags:

views:

452

answers:

3

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..])
+8  A: 
import Data.List
elemIndex 'b' "abc" === Just 1

A really good tool for finding haskell functions is Hoogle. Allows you to search by type signature among other things.

If you wanted to do everything in one pass I'd recommend Data.List.mapAccumL, passing the index of the largest number found so far along as the accumulator.

Will
+4  A: 

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.

So I should just ask SO how to do it, and in 15 minutes I'll get an answer and some snarky comments. Or - I could ask hoogle and get a useful response immidiately (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]
yairchu
Well it seems everyone except me was just born awesome now weren't they.But really, I didn't even know Hoogle existed, and I am still learning Haskell. I'll know better next time.
Jonno_FTW
@Jonno_FTW: I apologize for being snarky/cynical. Not everyone were born awesome, and some people are without being born that way. You can probably become awesome too. A good rule in Pythonesque programming is: if I find out that I'm coding the same thing 3 times, maybe I should make a function for it. In Haskellesque programming the constant is e instead of 3. Same rule also applies in meta-programming. If you find out that you need to find useful function aplenty, better try to find out if there is a better way to do this function searching process, and then discover Hoogle. mtfbwu
yairchu
A: 

If you want to find the index for which the function f is maximized on xs you can use

fst $ maximumBy snd $ zip [0..] (map f xs)

This first builds up a list of pairs [(0, f x_0), ... (n, f x_n)], finds the element with the largest second component and then returns the first component of that pair.

Tirpen