2
votes

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)).

2

2 Answers

4
votes

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.

3
votes

I'm sure there are more efficient ways of doing it, like the unsafe_blit approach String.concat is using, but a simple fold is at least an improvement over option 2:

Array.fold_left (fun acc s -> acc ^ s) "" arr

Reason/BuckleScript benchmark