19

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.

2 Answers 2

39

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..]
Sign up to request clarification or add additional context in comments.

Comments

33

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

2 Comments

Having indices at your disposal is a pretty common requirement when processing lists (e.g. for error reporting).
There are many uses for an index when processing a list that have nothing to do with using a suboptimal algorithm. So it is a very uncertain sign.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.