How can I convert a char list to a string in OCaml?
I have a char list ['a';'b';'c']
How do I convert this to the string "abc"?
thanks x
+3
Aditya Agrawal
source
to share
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
ivg
source
to share
let cl2s cl = String.concat "" (List.map (String.make 1) cl)
+4
Jeffrey scofield
source
to share