Finding index of element in a list in Haskell?

前端 未结 5 559
有刺的猬
有刺的猬 2021-01-03 18:36

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))) n         


        
5条回答
  •  情歌与酒
    2021-01-03 19:34

    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
    
    
    
    $ # 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]
    

提交回复
热议问题