Index of element in list in Haskell

haskell, indexing, list

Solution

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

Problem

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.

Original source