'Iterate over a list while tracking index?
I was just wondering if there was a way to iterate over a list while also keeping track of its index in OCaml? That would be really useful - I'm trying to stagger each element of a list by its index value. Thanks.
Solution 1:[1]
There is a function List.iteri that iterates over a list while supplying the index of each element. But if you want to generate a new list, it might be more appropriate to use List.mapi, which supplies the index of each element and builds up a new list (of the same size).
# List.mapi (fun index element -> element + index) [0;1;2;3];;
- : int list = [0; 2; 4; 6]
Documentation on OCaml List iterator functions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
