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 ?

  • \$\begingroup\$ My immediate thought is that you can abstract this out using a functor. \$\endgroup\$
    – Chris
    Dec 1, 2022 at 2:09


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.