I like OCaml because it is a pragmatic language that encourages a functional style, but doesn’t disallow mutability, which is necessary to implement many algorithms and data structures. However, OCaml’s standard library is centered around functional programming (for example, it has Lisp/ML-style cons linked lists, but not mutable doubly linked lists). I don’t think this is necessarily a bad thing, but sometimes, when I need to reach for a mutable data structure, I’m not sure where to go.
Recently, I needed a doubly linked list that specifically allowed for O(1) insertion and deletion given a reference to a node. I found opam - lwt-dllist, which supported removing nodes but not inserting a new node in front of or behind a given node. I also found Batteries user guide : BatDllist, which was a circular linked list and didn’t support empty lists. It seems to treat nodes as the list itself, with no “owner” of the nodes. I ended up rolling my own doubly linked lists.
Also consider dynamic arrays. opam - bheap rolls its own dynamic array: bheap/binary_heap.ml at 46f0f779d8acaf51fee488d350ffb490c7cec79b · backtracking/bheap · GitHub. Meanwhile, there is a standalone dynamic array package opam - vector, which requires the user to provide a dummy value, opam - vec, which uses Obj.magic
, and batteries-included/batDynArray.mlv at master · ocaml-batteries-team/batteries-included · GitHub, which uses Obj.magic
. There are different dynamic array libraries with their own pros and cons, and additionally, if I needed to use bheap and vec, I would have two implementations of dynamic arrays in my program, one internal to bheap.
If I just need a single data structure such as a doubly linked list or a dynamic array, I would also feel reluctant to pull in an entire standard library “extension” such as Batteries or Containers.
I wonder if other people experienced the need to use a common mutable data structure that wasn’t in the standard library and didn’t have one library that the majority of the ecosystem “agreed” upon? Did you have to choose between several libraries? Did you ultimately roll your own? How people would feel if the standard library included more common imperative data structures?
(As a side note, if people ever agree on one dynamic array library, I hope people don’t call it “vector.” The designer of the C++ vector library chose the name because it resembled “vectors” in Lisp, but this was a design mistake and a distortion of the mathematical notion of vector: stl - Why is a C++ Vector called a Vector? - Stack Overflow)