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 slconcatenates the list of stringssl, inserting the separator stringsepbetween 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)).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With