Take the 2-minute tour ×

I am pretty new to Haskell. so this might be a bit silly.

What I want is to do something like:

map (\x -> x + **position in list**) [0, 0, 0] => [1, 2, 3]

How can this be done?

share|improve this question
add comment

2 Answers

up vote 9 down vote accepted

The easiest way to get indexes is to zip your list with [0..] (or [1..] if you want 1-based indexes), for example:

> zipWith (\i x -> x + i) [1..] [0, 0, 0]
share|improve this answer
It works well, thank you! Do you know if there is any way to use it with positions in reverse? (the result would be [3, 2, 1] instead) I have tried by using 'length list' but it seems that it is not correct. –  cgf May 16 '13 at 13:48
@cgf: Is this the problem? –  hammar May 16 '13 at 13:52
Yes, that was it. Thank you so much! –  cgf May 16 '13 at 14:01
add comment

For the moment, let's assume you want to pair each element up with its position in the list. the easy way to do that is:

λ> zip [0..] [0, 0, 0]

If all you really want is the indices, then all you need is the first n elements of [0..], where n is the length of the input list. So...

λ> let xs = [0,0,0]
λ> [0..length xs - 1]

Or, equivalently,

λ> take (length xs) [0..]
share|improve this answer
A lazier method, which also works for infinite lists, is to use zipWith const [0..]. –  hammar May 16 '13 at 13:43
Good answer, but @hammar was slightly faster. Thank you! –  cgf May 16 '13 at 14:02
add comment

Your Answer


