user192837465
user192837465

Reputation: 215

Index of element in list in Haskell

How can I get the index of the element I am at in haskell when I am using map ?

For example I have this list l = "a+bc?|(de)*fg|h" and I want to know the exact index of the element I am at when I use the map or scanl function.

Upvotes: 19

Views: 18768

Answers (2)

Fred Foo
Fred Foo

Reputation: 363567

Amending Nikita Volkov's answer, you can use a function such as:

-- variant of map that passes each element's index as a second argument to f
mapInd :: (a -> Int -> b) -> [a] -> [b]
mapInd f l = zipWith f l [0..]

Upvotes: 38

Nikita Volkov
Nikita Volkov

Reputation: 43310

First of all, if you need an index when processing a list it is a certain sign that you're implementing a suboptimal algorithm, because list is not an index-based structure like array. If you need to deal with indexes you better consider using a vector instead.

Concerning your actual question, you can pair the items of your list with incrementing ints with the following code and then map over the result:

Prelude> zip [0..] "a+bc?|(de)*fg|h" :: [(Int, Char)]
[(0,'a'),(1,'+'),(2,'b'),(3,'c'),(4,'?'),(5,'|'),(6,'('),(7,'d'),(8,'e'),(9,')'),(10,'*'),(11,'f'),(12,'g'),(13,'|'),(14,'h')]

Upvotes: 33

Related Questions