I want to add a unique ID to every element in a collection (before output it as a JSON object).

A collection can be any set of items, as long as it has a map method implemented (Array, List and other custom collections such as trees comply with this requirement).

(** For a collection 'a t returns a collection of type (int, 'a) t *)
let add_indices_to_collection map collection =
  let index = ref (-1) in
  let add_index_to_element e =
    index := !index + 1 ;
    (!index, e)
  map add_index_to_element collection

And I can invoke it later per example with :

 CollectionHelper.add_indices_to_collection NonBinaryTree.map my_tree

It seems a little bit clumsy to me, is there a better way to do it ?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.