在Haskell的列表中查找元素的索引? [英] Finding index of element in a list in Haskell?

查看:131
本文介绍了在Haskell的列表中查找元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Haskell 中有一个函数,它可以找到指数的最大值一个列表:

  prob99 =最大$ map(\ xs  - >(head xs)^(head(tail xs) ))数字

我需要找到的是这个最大值在结果列表中的位置。编辑:我找到了这样的解决方案:

  n = [[519432,525806],[632382,518061] .... 
prob99b [a,b] = b *(log a)
answer = snd $最大(zip(map prob99b n)[1 ..])


解决方案

如何找到最大元素的索引?如何尝试所有索引并检查它们是否是最大值?

  ghci>让maxIndex xs = head $ filter((==最大xs)。(xs !!))[0 ..] 

但是这听起来像某个函数已经存在的东西。如果我使用现有的函数,我的代码将更具可读性,可维护性,甚至更高效。



所以我应该问一下如何去做, 15分钟我会得到一个答案和一些snarky评论。或者 - 我可以问hoogle并立即得到一个有用的回应(如Will建议)

  $ hoogleOrd a => [ a]  - > Int|头部

<无关>>

$#hmm,所以没有函数给我指定最大值,
$#但是如何找到一个特定的元素,并且我给它最大值?
$ hooglea - > [a] - > Int| head
Data.List elemIndex :: Eq a => a - > [a] - >也许Int
Data.List elemIndices :: Eq a => a - > [a] - > [Int]


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..])

解决方案

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]

这篇关于在Haskell的列表中查找元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆