Reputation: 161
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.
Upvotes: 1
Views: 1995
Reputation: 66803
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.
Upvotes: 4