[英]Get the Index of elements in list in Haskell
I have a list [4539, 5646, 6547, 7546]
.我有一个列表
[4539, 5646, 6547, 7546]
。
How can i to get the index of every element ?我怎样才能得到每个元素的索引?
index of 4539 --> 0索引 4539 --> 0
index of 5646 --> 1索引 5646 --> 1
index of 6547 --> 2索引 6547 --> 2
index of 7546 --> 3索引 7546 --> 3
-- >> elemIndex 4539 [4539, 5646, 6547, 7546]
-- 0
-- >> elemIndex 5646 [4539, 5646, 6547, 7546]
-- 1
-- >> elemIndex 6547 [4539, 5646, 6547, 7546]
-- 2
elemIndex :: Eq a => a -> [a] -> Int
What should happen when the element is not found?找不到元素时会发生什么?
>> elemIndex 20 []
*** Exception: elemIndex: empty list
The usual solution is to wrap the index in Maybe
.通常的解决方案是将索引包装在
Maybe
中。 This elemIndex
function exists in Data.List
.此
elemIndex
函数存在于Data.List
中。
-- >> elemIndex 4539 [4539, 5646, 6547, 7546]
-- Just 0
-- >> elemIndex 5646 [4539, 5646, 6547, 7546]
-- Just 1
-- >> elemIndex 6547 [4539, 5646, 6547, 7546]
-- Just 2
-- >> elemIndex 20 []
-- Nothing
elemIndex :: Eq a => a -> [a] -> Maybe Int
Use elemIndices
if you want to return a list of occurrences.如果要返回出现的列表,请使用
elemIndices
。
-- >> elemIndices 'o' "ooookay"
-- [0,1,2,3]
elemIndices :: Eq a => a -> [a] -> [Int]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.