Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 266
user192837465 Avatar asked Apr 24 '13 12:04

user192837465


2 Answers

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..]
like image 194
Fred Foo Avatar answered Oct 11 '22 21:10

Fred Foo


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')]
like image 25
Nikita Volkov Avatar answered Oct 11 '22 21:10

Nikita Volkov