Haskell程序在列表中查找元素的位置 [英] Haskell program to find the position of an element in a list
问题描述
我需要编写一个函数来查找列表中某个特定元素的位置。
我写的是这样的:
findPos list elt | list == [] = -1
|头目列表== elt = 0
|否则= 1 +(findPos(tail list)elt)
但是如何处理元素在列表中重复?
例如: list = [2,4,9,4,8]
,我想要元素4的位置,然后有2个位置:第二和第四。如何才能做到这一点?
您应该为匹配的元素返回一个懒惰评估的索引列表。
这样做的简单方法是首先使用 zip [0 ..]
索引列表,然后过滤在第二个元素上压缩列表,并最终删除第二个元素只是为了保留索引。
- 第一个版本
findPos list elt = map fst $ filter((elt ==).snd)$ zip [0 ..] list
- 使用列表解析的第二个版本
findPos list elt = [index | (index,e)< - zip [0 ..] list,e == elt]
I need to write a function to find the position of one specific element in a list. i was writing like this:
findPos list elt | list == [] = -1
| head list == elt = 0
| otherwise = 1 + (findPos (tail list) elt)
but how to do in the case that the element is repeated within the list?
For example: list= [2,4,9,4,8]
and i want the position of the element "4", then has 2 position : second and fourth. How would be a simply function for that?
You should return a lazy-evaluated list of indexes for elements that are matching.
The easy functional way of doing it is to index first the list using zip [0..]
then filter that zipped list on the second element and finaly remove the second elements just to keep the indexes.
-- first version
findPos list elt = map fst $ filter ((elt==).snd) $ zip [0..] list
-- second version, using list comprehensions
findPos list elt = [index | (index, e) <- zip [0..] list, e == elt]
这篇关于Haskell程序在列表中查找元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!