Search code examples
arraysocamlstring-concatenation

efficiently concatenate array of strings


The OCaml standard library provides the function String.concat

https://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html

val concat : string -> string list -> string

String.concat sep sl concatenates the list of strings sl, inserting the separator string sep between each.

Presumably this function exists to make easier to concatenate many strings together in time/space linear in the length of the strings.

Does similar functionality exist for arrays? In particular, is there a way to efficiently concatenate an array of strings together without either 1) writing a C extension and building a tricky intermediate structure or 2) effectively calling String.concat "" (Array.to_list arr)).


Solution

  • The best is to write your own concat function imitating String.concat. If you want something shorter, use a buffer to accumulate the result of your result (Array.iter (Buffer.add_string b) arr) — do not do repeated concatenations which will generate too many allocations.