How can I convert a char list to a string in OCaml?
2 answers
You can create a string of length equal to the length of the list, and then roll up over the list with a counter and initialize the string with the contents of the list ... But since OCaml 4.02, the string type started to shift towards immutability (and became immutable in 4.06), you must start thinking about strings as an immutable data structure. So, try another solution. There is a module Buffer
that is used specifically for building a string:
# let buf = Buffer.create 16;;
val buf : Buffer.t = <abstr>
# List.iter (Buffer.add_char buf) ['a'; 'b'; 'c'];;
- : unit = ()
# Buffer.contents buf;;
- : string = "abc"
Or, as a function:
let string_of_chars chars =
let buf = Buffer.create 16 in
List.iter (Buffer.add_char buf) chars;
Buffer.contents buf
+5
source to share